10

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!

3
  • 2
  • 1
    document.querySelector[All]()
    – Virus721
    Sep 20, 2013 at 8:58
  • Thanks guys, its all about having the knowledge of where to look heh..? but can I do - querySelector(div.ContainerDiv td tr p)? or just querySelector(div.containerDiv)?
    – user2703728
    Sep 20, 2013 at 9:00

1 Answer 1

29

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.

3
  • i am getting error Uncaught TypeError: document.querySelector(...).click is not a function
    – user14097926
    Jun 15, 2021 at 5:37
  • @prabhav Do you mean querySelectorAll().click is not a function as querySelector only returns the dom element or null and if it returned null you would have a different error message. If you did mean querySelectorAll it is because that returns a collection (wither or not any element is found) and it does not have a click method, you would need to access the individual items in the collection to access their click method, eg querySelectorAll(...)[1].click() Jun 15, 2021 at 20:45
  • no i just used document.querySelector(...).click and that is the error message i got from i just copy paste the error
    – user14097926
    Jun 16, 2021 at 4:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.