How to get a set of DIV identifiers without jQuery

I have a bunch of links with identifiers that correspond to classes attached to other links. I pass the link identifier as a variable, and then use this variable to find other links by class with JavaScript. Here is a sample code:

var elements = document.getElementsByClassName(id); for(var i=0; i<elements.length; i++){} 

So far, so good that I can do whatever I want for these related links. However, now I want to get the identifiers of the div in which these links are located. Is there a way to use JavaScript to search for id div links without using jQuery?

Before asking, why not just use jQuery? I am new to this and have not yet learned jQuery. Also, I would like to understand how to do things in JavaScript before I try to learn something else.

+4
source share
2 answers

To access the parent id, you can use:

 var elementId = elements[i].parentNode.id; 

See here for more info: Getting the parent div of an element

To find the closest parent of the DIV, you should do something like this:

 var elements = document.getElementsByClassName(id); for(var i=0; i<elements.length; i++){ var parent = elements[i].parentNode; while (parent.localName != null && parent.localName.toLowerCase() != "div") { parent = parent.parentNode; } if (parent != null && parent.id != null) { var parentId = parent.id; alert(parentId); } } 

EDIT: A null check is simply added if the class is NOT contained in any DIV.

Here is the test I used:

 <html> <body> <div id="asdf"> <a href="#" class="blah">1</a> <a href="#" class="blah">2</a> </div> <div id="asdf2"> <span> <a href="#" class="blah">3</a> <a href="#" class="blah">4</a> </span> </div> <!-- These two won't cause an alert since no DIV surrounds them --> <a href="#" class="blah">5</a> <a href="#" class="blah">6</a> <div id="asdf3"> <span> <a href="#" class="blah">7</a> <a href="#" class="blah">8</a> </span> </div> <input type="button" onclick="run();return false;" value="Run" /> <script> // This will cause 6 alerts: asdf, asdf, asdf2, asdf2, asdf3, asdf3 function run() { var elements = document.getElementsByClassName("blah"); for(var i=0; i<elements.length; i++){ var parent = elements[i].parentNode; while (parent.localName != null && parent.localName.toLowerCase() != "div") { parent = parent.parentNode; } if (parent != null && parent.id != null) { var parentId = parent.id; alert(parentId); } } } </script> </body> </html> 
+3
source

You can use element.parentNode.id to get the attribute of the parent id element.

0
source

All Articles