OVE*_*ONE 191 html javascript getelementbyid
这应该很简单,但我遇到了麻烦.如何获取子元素的父div?
我的HTML:
<div id="test">
<p id="myParagraph">Testing</p>
</div>
Run Code Online (Sandbox Code Playgroud)
我的JavaScript:
var pDoc = document.getElementById("myParagraph");
var parentDiv = ??????????
Run Code Online (Sandbox Code Playgroud)
我会想document.parent或parent.container会工作,但我一直在not defined犯错误.请注意,它pDoc是定义的,而不是它的某些变量.
有任何想法吗?
PS我希望尽可能避免使用jQuery.
T.J*_*der 307
你正在寻找parentNode,Element继承自Node:
parentDiv = pDoc.parentNode;
Run Code Online (Sandbox Code Playgroud)
方便参考:
Rob*_*obG 32
如果您正在寻找比直接父级更远的特定类型的元素,您可以使用一个上升到DOM的函数,直到它找到一个,或者不是:
// Find first ancestor of el with tagName
// or undefined if not found
function upTo(el, tagName) {
tagName = tagName.toLowerCase();
while (el && el.parentNode) {
el = el.parentNode;
if (el.tagName && el.tagName.toLowerCase() == tagName) {
return el;
}
}
// Many DOM methods return null if they don't
// find the element they are searching for
// It would be OK to omit the following and just
// return undefined
return null;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
256720 次 |
| 最近记录: |