Home > OS >  How to insert a <p> tag's text into its parent element as a data attribute?
How to insert a <p> tag's text into its parent element as a data attribute?

Time:07-01

I have this HTML:

<div  data-item="">
  <img src="">
  <p>table</p>
</div>
<div  data-item="">
  <img src="">
  <p>table</p>
</div>
<div  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  data-item="table">
  <img src="">
  <p>table</p>
</div>
<div  data-item="table">
  <img src="">
  <p>table</p>
</div>
<div  data-item="others">
  <img src="">
  <p>others</p>
</div>

CodePudding user response:

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  data-item="">
  <img src="">
  <p>table</p>
</div>
<div  data-item="">
  <img src="">
  <p>table</p>
</div>
<div  data-item="">
  <img src="">
  <p>others</p>
</div>

  • Related