简体   繁体   English

JS中如何遍历DOM?

[英]How to traverse through DOM in JS?

I have a function that I call to get the data of the alt attribute when an image is clicked.我有一个 function 在单击图像时调用它以获取 alt 属性的数据。 Here's the function-这是功能-

document.addEventListener("click", function(e) {
    var a = e.target.closest("a[href]");
    if (a) {
       var img = e.target.closest("img[alt]")
       var alt = img.getAttribute("alt")
    }

I would like to know how can I traverse upwards to get the data in the 'h2' tag of the same section after my function is called.我想知道在调用 function 之后如何向上遍历以获取同一部分的“h2”标签中的数据。

Here's the structure of the section-这是该部分的结构-

<section>
  <div>
    <div>
      <h2> Some data </h2>
    </div>
    <a href="#">
    <img border="0" alt="Hello there" src="test.jpg" width="100" height="100">
  </div>
</section>

Any help is appreciated.任何帮助表示赞赏。 Thanks in advance for your help.在此先感谢您的帮助。

Use parentNode to get the parent node and query the h2 tag.使用parentNode获取父节点并查询 h2 标签。

document.addEventListener("click", function(e) {
    var a = e.target.closest("a[href]");
    if (a) {
      var parentNode = a.parentNode;
      var h2 = parentNode.querySelector('h2');
      var title = h2.innerText;
      console.log(title);
      var img = e.target.closest("img[alt]")
      var alt = img.getAttribute("alt")
    }
})

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

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