Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Get Element From Path Not Class or Id

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!

like image 927
Phish Avatar asked Sep 20 '13 08:09

Phish


People also ask

How do you select an element without a class?

The :not CSS pseudo-class can be used to select elements that do not contain a specific class, id, attribute etc.

How do I find an element with a specific ID?

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.

How do I get a DOM path?

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 !==

Can I use get element by class?

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.


1 Answers

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.

like image 177
Patrick Evans Avatar answered Oct 27 '22 09:10

Patrick Evans