要访问父元素 ID,您可以使用:
var elementId = elements[i].parentNode.id;
有关更多信息,请参见此处:获取元素的父 div
要找到最近的 DIV 父级,您应该能够执行以下操作:
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);
}
}
编辑:刚刚添加了一些空检查,以防类不包含在任何 DIV 中。
这是我使用的测试:
<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>