Skip to content
Advertisement

How to insert a tag’s text into its parent element as a data attribute?

I have this HTML:

<div class="content_section_item" data-item="">
  <img src="">
  <p>table</p>
</div>
<div class="content_section_item" data-item="">
  <img src="">
  <p>table</p>
</div>
<div class="content_section_item" data-item="">
  <img src="">
  <p>others</p>
</div>

How do I make a loop that takes the inner text of every p tag and puts it into the data-item attribute of its respective div parent like this:

<div class="content_section_item" data-item="table">
  <img src="">
  <p>table</p>
</div>
<div class="content_section_item" data-item="table">
  <img src="">
  <p>table</p>
</div>
<div class="content_section_item" data-item="others">
  <img src="">
  <p>others</p>
</div>

Answer

Loop over the divs. In each div, use querySelector() to find the nested p, get its contents with .textContent, and assign that to the div’s data-item property.

document.querySelectorAll('div.content_section_item').forEach(
    div => div.dataset.item = div.querySelector('p').innerText
);
<div class="content_section_item" data-item="">
  <img src="">
  <p>table</p>
</div>
<div class="content_section_item" data-item="">
  <img src="">
  <p>table</p>
</div>
<div class="content_section_item" data-item="">
  <img src="">
  <p>others</p>
</div>
Advertisement