![](/img/trans.png)
[英]How to show particular Text Lines in Italic format in the TextArea Tag in SAP Fiori Apps?
[英]How to change <p> tag text, without remove underline or italic format?
我有这种情况
"<p><strong><em><u>Allow Ship Partial</u></em></strong></p>"
我想更改<p>
文本,但如果使用$('p').text('another text')
它将删除文本格式。
有什么方法可以在不丢失格式的情况下做到这一点?
发生这种情况是因为您正在用另一个文本替换 p 的内容,而该文本恰好是
<strong><em><u>Allow Ship Partial</u></em></strong></p>
所以你甚至要替换格式标签。 你应该改用
$('p strong em u').text('another text')
甚至更好
$('p>strong>em>u').text('another text')
您也可以使用 CSS 来设置样式
标签
它看起来像这样
p {
font-weight: bold;
font-style: italic;
text-decoration: underline;
}
使用parentNode
p
的父节点,遍历子节点并将它们附加到parent
,然后删除原始节点。
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>
如果您的结构始终得到保证(我不相信),其他答案可能会解决您的问题,但您可以改为递归迭代子节点,直到找到文本节点。 完成后,替换内联文本。
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>
注意这个例子只是第一遍; 您最有可能需要检查边缘情况(例如是否找到文本节点等)。 我也没有使用 jQuery,因为大多数 jQuery 方法不包含文本节点。 如果您更喜欢该路由,您可以使用jQuery.contents()对其进行重构,在每次迭代时过滤掉非文本节点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.