Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
6
rated 0 times [  12] [ 6]  / answers: 1 / hits: 30506  / 11 Years ago, fri, september 20, 2013, 12:00:00

I am struggling to find an answer for this, I want a way to talk about an element, but because of the system I am adding to I do can not reference by its Id as it is dynamic. I can specify the class name of its containing div though... In essence what I am looking for is something along the lines of:



var disAb=document.getElementBySomething(div.ContainerDiv select)


When I mention the term 'path' I mean how I would reference it in CSS (see code reference).



Thank you guys!


More From » dom

 Answers
6

You want document.querySelector or document.querySelectorAll, then just reference it by its hierarchy path:



Sample HTML



<div class=ContainerDiv>
<table>
<tr>
<td>
<div>
<select>
<option>Some options</option>
</select>
</div>
</td>
</tr>
</table>
</div>


JS



Get single element



var select=document.querySelector(div.ContainerDiv table tr td div select);
select.id = someid;


For more than one element



var selects=document.querySelectorAll(div.ContainerDiv select);
selects[0].id = someid;


Of course you do not need each part of the hiearchy, for instance you could just use: div.ContainerDiv select or div.ContainerDiv table select etc.


[#75573] Thursday, September 19, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leog

Total Points: 225
Total Questions: 113
Total Answers: 118

Location: Oman
Member since Wed, Apr 12, 2023
1 Year ago
;