简体   繁体   English

遍历 DOM 元素并动态添加数据属性

[英]Iterate over DOM elements and dynamically add data-attributes

I have the following DOM structure and I need to get the text inside my h1 or h2 tag (but always first-child) and add that text value as as data-attribute to the second-child.我有以下 DOM 结构,我需要在我的 h1 或 h2 标记中获取文本(但总是第一个孩子)并将该文本值作为数据属性添加到第二个孩子。

<div class="my-item">
    <div class="mac">
        <h1>test123</h1>
        <div>p1</div>
    </div>
</div>
<div class="my-item">
    <div class="mac">
        <h2>test456</h2>
        <div>p2</div>
    </div>
</div>

So my DOM after JS should look like this:所以我在 JS 之后的 DOM 应该是这样的:

<div class="my-item">
<div class="mac">
    <h1>test123</h1>
    <div data-head="test123">p1</div>
</div>
</div>
<div class="my-item">
<div class="mac">
    <h2>test456</h2>
    <div data-head="test456">p2</div>
</div>
</div>

I attempted to do this by getting the list of all selectors and iterating over the list, but it wouldn't add the data-attributes and I don't see any console error.我试图通过获取所有选择器的列表并遍历列表来做到这一点,但它不会添加数据属性,而且我没有看到任何控制台错误。 I believe the way I'm doing it is unable to find the elements:我相信我这样做的方式是找不到元素:

 var items = document.querySelectorAll("div.my-item"); for (var i=0, max=items.length; i < max; i++) { var itemH = $( "div.body:first-child" ).find(items[i]); var itemP = $( "div.body:nth-child(2)" ).find(items[i]); itemP.setAttribute('data-head', itemH.text()); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="my-item"> <div class="mac"> <h1>test123</h1> <div>p1</div> </div> </div> <div class="my-item"> <div class="mac"> <h2>test456</h2> <div>p2</div> </div> </div>

When you use JQuery selectors, they return a JQuery wrapped set object, which is not a native object in JavaScript, so when you try to call setAttribute() on that JQuery object, you will get an error message in your developer's console. When you use JQuery selectors, they return a JQuery wrapped set object, which is not a native object in JavaScript, so when you try to call setAttribute() on that JQuery object, you will get an error message in your developer's console.

Really, JQuery is overkill for this problem.真的,JQuery 对于这个问题来说太过分了。 If you just locate each second child of the respective groups and loop over them, you can update its data-head attribute to include that div s previous sibling element's text using the dataset API .如果您只是定位各个组的每个第二个子元素并遍历它们,则可以使用dataset API更新其data-head属性以包含该div的前一个兄弟元素的文本。

 // Get all the second child elements within the my-item groups var items = document.querySelectorAll("div.my-item > div.mac >:nth-child(2)"); // Loop over the returned node list with the Array.forEach() API // which is simpler than for loops because there's no index you // have to manage. items.forEach(function(item){ // Set data-* attribute using the dataSet API item.dataset.head = item.previousElementSibling.textContent; console.log(item); });
 <div class="my-item"> <div class="mac"> <h1>test123</h1> <div>p1</div> </div> </div> <div class="my-item"> <div class="mac"> <h2>test456</h2> <div>p2</div> </div> </div>

You can directly target the <h1> and and <h2> elements inside the div with class .my-class like this:您可以使用 class .my-class直接定位 div 内的<h1><h2>元素,如下所示:

 $(".my-item h1, .my-item h2").each(function() { $(this).next("div").attr("data-head", $(this).text()); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="my-item"> <div class="mac"> <h1>test123</h1> <div>p1</div> </div> </div> <div class="my-item"> <div class="mac"> <h2>test456</h2> <div>p2</div> </div> </div>

Update: As mentioned in the comments, the header tags could not only be h1 and h2, but everything up to h6.更新:正如评论中提到的,header 标签不仅可以是 h1 和 h2,而且可以是 h6。 To target all header tags, it's possible to use :header :要定位所有 header 标签,可以使用:header

 $(".my-item:header").each(function() { $(this).next("div").attr("data-head", $(this).text()); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="my-item"> <div class="mac"> <h1>test123</h1> <div>p1</div> </div> </div> <div class="my-item"> <div class="mac"> <h2>test456</h2> <div>p2</div> </div> </div>

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

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