首页 > 解决方案 > 通过从 DOM 读取值来添加数据属性

问题描述

我有以下 html 结构,我正在尝试获取 h 标签的文本并在相应的标签中添加为 data- 属性:

<div class="content">
<div class="body">
    <h1>foo</h1>
    <p>para-test1</p>
    <p>para-test2</p>
    <div class="link"> 
        <a href="#">anchor1</a>
        <a href="#"">anchor2</a>
        <a href="#">anchor3</a>
    </div>
</div>
</div>
<div class="content">
<div class="body">
    <h1>bar</h1>
    <p>para-test3</p>
    <div class="link"> 
        <a href="#"">anchor4</a>
    </div>
</div>
</div>

所以'foo'应该设置为锚1、2、3元素的数据属性值,'bar'应该设置为锚4的数据属性值。像这样:

<a data-custom="foo" href="#">anchor1</a>
<a data-custom="foo" href="#"">anchor2</a>
<a data-custom="foo" href="#">anchor3</a>

<a data-custom="bar" href="#">anchor4</a>

我试图迭代元素,但我在第二个循环中感到震惊。

$(".content .body").each(function() {
$(this).find(".link").attr("data-hN", $(this).next(":header").text());
});

标签: javascripthtmljquerycss

解决方案


您的 HTML 中有两次额外的双引号。但是,修复这个问题和前面的 JQuery(这对于这样一个微不足道的任务来说是多余的),请参阅下面的内联评论:

// Loop over the links
document.querySelectorAll("div.link > a").forEach(function(item){
  // Set the current link data-custom attribute to the nearest
  // .body ancestor and the first heading element within that text
  item.dataset.custom = item.closest(".body").querySelector(":first-child").textContent;
  console.log(item);
});
<div class="content">
<div class="body">
    <h1>foo</h1>
    <p>para-test1</p>
    <p>para-test2</p>
    <div class="link"> 
        <a href="#">anchor1</a>
        <a href="#">anchor2</a>
        <a href="#">anchor3</a>
    </div>
</div>
</div>
<div class="content">
<div class="body">
    <h1>bar</h1>
    <p>para-test3</p>
    <div class="link"> 
        <a href="#">anchor4</a>
    </div>
</div>
</div>


推荐阅读