Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
82
rated 0 times [  86] [ 4]  / answers: 1 / hits: 23663  / 11 Years ago, sat, march 2, 2013, 12:00:00

Is there any alternative solution (in JavaScript) for document.getElementById(); to select a specific element, specifying both the class and id ?



for example I have such a content:



<a class=q_href onclick=showQuestion(1)>Question 1:</a>
<div class=q_content id=1></div>

<a class=q_href onclick=showQuestion(2)>Question 2:</a>
<div class=q_content id=2></div>


And I want to select the corresponding div under the Question X link in the function



function showQuestion(id)
{
var thediv = GetByClassAndId(q_content,id); // how to implement this function ?
WriteQuestionIn(thediv); //Ajax
}


Thanks in advance.


More From » html

 Answers
8

Since ID is always unique (unless u make a mistake) u have no need to use both class and id to select the element.

Such an approach is not correct, and should be avoided at all cost.



What I suspect is your problem, is that the ID is only a number. Try adding a prefix which is a letter. Do view source to this page to see examples.



<a class=q_href onclick=showQuestion(1)>Question 1:</a>
<div class=q_content id=q1></div>

<a class=q_href onclick=showQuestion(2)>Question 2:</a>
<div class=q_content id=q2></div>

function showQuestion(id)
{
var thediv = document.getElementById(q+id);
WriteQuestionIn(thediv); //Ajax
}

[#79891] Thursday, February 28, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gideonb

Total Points: 187
Total Questions: 101
Total Answers: 86

Location: North Korea
Member since Mon, Feb 27, 2023
1 Year ago
;