Skip to content
Advertisement

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

I have this HTML:

JavaScript

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:

JavaScript

Advertisement

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.

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement