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> <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>
source share