获取元素的父div [英] Getting the parent div of element

查看:96
本文介绍了获取元素的父div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该很简单,但我遇到了麻烦。如何获得子元素的父级div?

HTML

 < div id =test> 
< p id =myParagraph>测试< / p>
< / div>


$ 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆