gpt4 book ai didi

javascript - 如何在 html js 中获取类(class)家长 ID(无 jQuery)

转载 作者:行者123 更新时间:2023-12-01 00:10:08 25 4
gpt4 key购买 nike

我有课。我怎么知道这个类(class)的家长id。

最佳答案

HTMl 中的元素只能有一个父节点。我不确定您是否想要检索示例中的 grandParent 类的 id。如果您想检索所有祖先节点的 id,请更新问题。

const child = document.querySelector('.child') // Selecting the class you want to work with.
console.log(child);

const parent = child.parentElement.getAttribute('id') // Getting id of parent node.
console.log('parent id: ', parent);
  <div id='1' class='grandParent'>
<div id='2' class='parent'>
<div id='3' class='child'>
Hi
</div>
</div>
</div>

关于javascript - 如何在 html js 中获取类(class)家长 ID(无 jQuery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60132949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com