简体   繁体   中英

How to change <p> tag text, without remove underline or italic format?

I have this situation

"<p><strong><em><u>Allow Ship Partial</u></em></strong></p>"

I want to change the <p> text but if use $('p').text('another text') it will be remove the text format.

There is any way that I can do that without loose the format?

This happens because you're replacing the content of p with another text which happens to be

<strong><em><u>Allow Ship Partial</u></em></strong></p>

So you're replacing even the format tags. You should instead use

$('p strong em u').text('another text')

or even better

 $('p>strong>em>u').text('another text')

You could alternatively use CSS for the styling of the

tag

it would look something like this

p {
    font-weight: bold;
    font-style: italic;
    text-decoration: underline;
}

Grab the parent of p using parentNode , iterate over the child nodes and append them to the parent , and then delete the original node.

    while(c.hasChildNodes()) p.appendChild(c.firstChild);
    p.removeChild(c);

 let c = document.querySelector("p"), p = c.parentNode; while(c.hasChildNodes()) p.appendChild(c.firstChild); p.removeChild(c);
 <p><strong><em>Hi</em></strong></p>

While the other answers may tackle your problem if your structure is always guaranteed (which I don't believe it is), then you can instead iterate recursively over child nodes until you find a text node. Once you have that, replace the text inline.

 function findTextElement(element) { for (let i = 0, n = element.childNodes.length; i < n; i++) { const child = element.childNodes[i]; if (child.nodeType !==3) { return findTextElement(child); } return child; } } const ps = document.querySelectorAll('p'); [].forEach.call(ps, (node, i) => { const textElement = findTextElement(node); textElement.parentNode.innerHTML = `New String ${i + 1} retains formatting`; });
 <p><strong><em><u>Allow Ship Partial 1</u></em></strong></p> <p><em><strong>Allow Ship Partial 2</strong></em></p> <p><u>Allow Ship Partial 3</u></p> <p>Allow Ship Partial 4</p>

Note this example is just a first pass; there are most likely edge cases you will need to check against (like whether or not a text node is found, etc.). I've also not used jQuery as most jQuery methods do not include text nodes. You may be able to refactor this using jQuery.contents() if you prefer that route, filtering out non-text nodes on each iteration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM