Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get element by both id and class

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.

like image 894
marvin Avatar asked Mar 02 '13 02:03

marvin


2 Answers

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
}
like image 110
Itay Moav -Malimovka Avatar answered Sep 27 '22 15:09

Itay Moav -Malimovka


you can try document.querySelector()

like document.querySelector(".q_content#2") use the para like css selector..

like image 31
uoryon Avatar answered Sep 27 '22 17:09

uoryon