Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
How to insert a <p> 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>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!