简体   繁体   English

如何在Javascript中找到h1标签数组的父ID?

[英]How to find the parent id's of an h1 tag array in Javascript?

I have something like this in my HTML: 我的HTML中有类似的内容:

<div id="div0"></div>
<div id="div1"><h1>h1(0)</h1></div>
<div id="div2"><h1>h1(1)</h1></div>
<div id="div3"><h1 class="center">h1(2)</h1></div>
<div id="div4"><h1>h1(3)</h1><h1>h1(4)</h1></div>

My Javascript: 我的Javascript:

var tags=document.getElementsByTagName('h1');
console.log(tags) =
  HTMLCollection[h1,h1,h1.center,h1,h1]

I'm trying to figure out how to get the id of the parent of, say, tags[2], which would be "div3". 我试图弄清楚如何获取tag [2]的父级的ID,该ID为“ div3”。

You can try:- 你可以试试:-

tags[2].parentElement.id 

parentElement parentElement

or 要么

tags[2].parentNode.id

parentNode parentNode

Both are almost similar, one difference is when a the Node's parentNode is not an element. 两者几乎相似,不同之处在于Node的parentNode不是元素。 If so, parentElement will be null. 如果是这样,parentElement将为null。 eg;- if you are looking at the HTML element, parentNode will return you documentElement whereas parentElement will return null. 例如;-如果您正在查看HTML元素,则parentNode将返回documentElement而parentElement将返回null。

Small fiddle to demonstrate the main difference here 小提琴在这里展示主要区别

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM