我有一个特定的 DIV 结构,中间有一个 anchor 标记。单击链接时,我需要获取父级 div
中另一个 span
元素的值并执行某些操作(例如,提醒它)。
html是这样的:
...
<div id="div1">
...
<span>This is reqd</span>
...
<a href="#">Click Me </a>
...
</div>
...
整个div
在页面中重复了很多次。
当我点击 a
时,我想提醒“This is reqd”。
HTML可以这样搜索吗?
最佳答案
对于单个 span 元素,应该很容易,。只需在单击链接时调用 myFunction(this) 并像这样操作 DOM:
function myFunction(currObj){
var parentofSelected = currObj.parentNode; // gives the parent DIV
var children = parentofSelected.childNodes;
for (var i=0; i < children.length; i++) {
if (children[i].tagName = "span") {
myValue= children[i].value;
break;
}
}
alert(myValue); // just to test
} // end function
希望这能奏效。它对我有用!!
关于javascript - 在javascript中获取附近的 sibling ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14477791/