stdio.h
stdio.h

Reputation: 126

add data- attributes by reading values from DOM

I have the below html structure and I'm trying to get the text of h tags and add as a data- attribute in the corresponding tags:

<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>

So 'foo' should be set as a data attribute value for anchor 1,2,3 elements and 'bar' should be set as a data attribute value for anchor 4. Something like this:

<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>

I tried to iterate over the elements and I'm struck at the second loop.

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

Upvotes: 0

Views: 45

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65873

You have an extra double quote two times in your HTML. But, fixing that and foregoing JQuery (which is overkill for such a trivial task), see comments inline below:

// 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>

Upvotes: 1

Related Questions