Phish Phish - 7 months ago 13
Javascript Question

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!


you want document.querySelector or document.querySelectorAll then just reference it by its hierarchy path

Sample HTML

<div class="ContainerDiv">
              <option>Some options</option>


Get single element

var select=document.querySelector("div.ContainerDiv table tr td div select"); = "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.