简体   繁体   English

使用Java进行Dom遍历

[英]Dom Traversal using Javascript

How can i access <h2> tag. 我如何访问<h2>标签。 My current selection is a <span> element which is child of button. 我当前的选择是<span>元素,它是按钮的子元素。 i tried but was only able to get to the parent which is button. 我试过了,但只能去按钮的父母。

Please note i have multiple <Span> element on the page 请注意,我在页面上有多个<Span>元素

please note i purely need java script since i am using custom java script which is in Google tag manager. 请注意,我纯粹需要Java脚本,因为我使用的是Google标记管理器中的自定义Java脚本。

so basically iam using the below code. 所以基本上IAM使用下面的代码。 just a heads up the {{clickelemet}} here is the <span> element <> function() { 只是{{clickelemet}}的标题,这里是<span>元素<> function(){

  var el = {{Click Element}}.parentElement.querySelector('h2');

  return el ? el.textContent || el.innerText : undefined;

}

---------------HTML elements ----------------------- --------------- HTML元素-----------------------

<div class="col-12 col-md-10 offset-md-1">
                                    <h2>Blockchain – Opportunities &amp; Challenges across Multiple Industries</h2>
                                    <p>It began with Bitcoin, but now it has spread. Blockchain has the potential to radically transform the way industries do business. Here are some examples of success and challenges as blockchain inserts itself into transactions and process.</p>
                                    <button class="panel__link panel__link--btb" aria-expanded="false" aria-controls="panel-1">
                                        <i>+</i> <span>Expand article</span>
                                    </button>
                                </div>

Thanks for the support. 感谢您的支持。

document.getElementsByTagName("h2");

Also

document.querySelector('h2');

Retrieves the first h2 in the DOM 检索DOM中的第一个h2

I guess, you're adding a click event on your button element. 我想,您是在按钮元素上添加了click事件。 If so, then, the click event can also be actually fired on its child elements (ie span ). 如果是这样,那么click事件也可以实际在其子元素(即span)上触发。 So, In order to get the button element's parent, you've to check the event.target : 因此,为了获取button元素的父元素,您必须检查event.target:

document.querySelector('button.panel__link').addEventListener('click', 
    function(e){
      var el, elContent;
      if(e.target.className === "panel__link panel__link--btb"){
         el = e.target.parentElement.querySelector('h2');
         elContent = el ? (el.textContent || el.innerText) : undefined;
      }

});

If you have only one in your page, use 如果页面中只有一个,请使用

getElementsByTagName("h2")[0]; If you have multiple tags, 如果您有多个标签,

var parent = document.getElementById('<your-class>');
var child = parent.getElementById('<your-class>')[0];

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

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