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!
The :not CSS pseudo-class can be used to select elements that do not contain a specific class, id, attribute etc.
getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.
getElementById('nodeA'); // Function to getPath function getPath(root, node) { // receiving a root element and a node element const path = []; // To save the path of the node element that need to get to the root element // Starting to get the path from bottom (nodeA) to top (rootA) while (node !==
You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class name(s). Warning: This is a live HTMLCollection . Changes in the DOM will reflect in the array as the changes occur.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With