获取元素的父div [英] Getting the parent div of element
问题描述
HTML
< div id =test>
< p id =myParagraph>测试< / p>
< / div>
$ c
$ b JavaScript
var pDoc = document.getElementById(myParagraph);
var parentDiv = ??????????
我会认为 document.parent
或 parent.container
可以工作,但我会保留获得未定义
错误。请注意, pDoc
是被定义的,而不是它的某些变量。
有什么想法?
PS如果可能的话,我宁愿避免使用jQuery。
解决方案您正在寻找 parentNode
, Element
继承自 Node
:
parentDiv = pDoc.parentNode;
方便的参考资料:
- DOM2 Core 规范 - 得到所有专业人士的充分支持浏览器
- DOM2 HTML 规范 - DOM和HTML之间的绑定
- DOM3 Core 规范 - 一些更新,并非所有主流浏览器都支持
- HTML5规范 - 现在已有DOM / HTML绑定
This should be really simple but I'm having trouble with it. How do I get a parent div of a child element?
HTML
<div id="test>
<p id="myParagraph">Testing</p>
</div>
JavaScript
var pDoc = document.getElementById("myParagraph");
var parentDiv = ??????????
I would have thought document.parent
or parent.container
would work but I keep getting not defined
errors. Note that the pDoc
is defined, just not certain variables of it.
Any ideas?
P.S. I would prefer to avoid jQuery if possible.
解决方案 You're looking for parentNode
, which Element
inherits from Node
:
parentDiv = pDoc.parentNode;
Handy References:
- DOM2 Core specification - well-supported by all major browsers
- DOM2 HTML specification - bindings between the DOM and HTML
- DOM3 Core specification - some updates, not all supported by all major browsers
- HTML5 specification - which now has the DOM/HTML bindings in it
这篇关于获取元素的父div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!