I need to somehow unwrap these lines of text and append them as plain text to the p
element without all the divs, using js. How can i do that?
The result i am after is to go from this:
<p>
<div class="line">
<div>
some text
</div>
</div>
<div class="line">
<div>
some text
</div>
</div>
<div class="line">
<div>
some text
</div>
</div>
</p>
to this:
<p>
some text some text some text
</p>
Below is what i am trying right now, which is not much at the moment.
const lines = [...document.querySelectorAll('.line')]
lines.forEach((el, index) => {
})
3
Answers
You can use a loop to build an array from the text content contained within the
.line div
elements. You can then use that to set the content of thep
.Note that the following example also calls
remove()
on the.line
div elements, as they are not contained within thep
because they are block-level elements, so the HTML as it stands is invalid:Let’s get the parent P so we can operate on it…
Now display and observe the differences between these three…
Which one has joined all the text contained in all the paragraph’s children?
A little exercise for you. 🙂
If I understood your question right, you want to get the text content of the parent
<p>
element.Add an
id
attribute to the element:Then access its text content wrapped out of element tags like this: