format paragraph <p>

Asked

Viewed 46 times

3

I run some js functions in a given text. adding classes and removing classes. The final html generates some breaks in the paragraph, like this:

<p style="text-align: left;">
“obviamente”
“ nem todos apoiam”
“ o brasil.”
</p>

I need to treat this paragraph to look like this:

<p style="text-align: left;">
“obviamente nem todos apoiam o brasil.”
</p>

Otherwise the next time I use the same function, it does not perform right (because I use regex).

Any idea how to treat this paragraph?

1 answer

3


These breaks are about Text Nodes. See example below (Inspecione the paragraph element):

const p = document.querySelector('p')

const text1 = document.createTextNode('text1 ')
const text2 = document.createTextNode('text2 ')
const text3 = document.createTextNode('text3')

p.appendChild(text1)
p.appendChild(text2)
p.appendChild(text3)

console.log('ChildNodes:', p.childNodes.length)
<p></p>

What you can do is use the method normalize, your advantage is that if you have other tags in the middle of the Text Nodes, they will preserve themselves.

const p = document.querySelector('p')

const text1 = document.createTextNode('text1 ')
const text2 = document.createTextNode('text2 ')
const text3 = document.createTextNode('text3')

p.appendChild(text1)
p.appendChild(text2)
p.appendChild(text3)

p.normalize()

console.log('ChildNodes:', p.childNodes.length)
<p></p>

  • 1

    @Lukenegreiros se tem dúvidas sobre como aceitar a resposta, dê uma olhada aqui: https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta

Browser other questions tagged

You are not signed in. Login or sign up in order to post.