gpt4 book ai didi

javascript - 将 p 标签添加到无格式文本 - 纯 JavaScript

转载 作者:行者123 更新时间:2023-12-02 21:36:41 30 4
gpt4 key购买 nike

我有一个内容,其内部元素文本不包含任何 html 标签。如何使用纯 JavaScript 添加“p”标签? jQuery 解决方案已经存在,但我需要简单的 JavaScript 解决方案。我已经尝试过 “nodeType”“innerText”“textContent”“innerHTML”

jQuery 解决方案是

$('.arfaa').each(function() { 
$(this).contents().filter(function() {
return this.nodeType === 3;
}).wrap('<p></p>');
});

如何通过纯 JavaScript 解决这个问题?

<div class="content">

This is just a line of text.

<div><img src="demo.jpg" alt=""></div>

This is just a line of text.

<br><br>

<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ul>

<br><br>

This is just a <a href="#">line</a> of text.

<br><br>

This is just a <span>line of text</span>.

<br><br>

<figure><img src="demo.jpg" alt="text">
<figcaption>img description</figcaption>
</figure>

This is just a line of text.

<br><br>

This is just a line of text.

<table><tbody>
<tr><th>A</th><td>A value</td></tr>
<tr><th>B</th><td>B value</td></tr></tbody>
</table>

<br><br>

This is just a line of text.

</div>

预期输出

<div class="content">

<p>This is just a line of text.</p>

<div><img src="demo.jpg" alt=""></div>

<p>This is just a line of text.</p>

<br><br>

<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ul>

<br><br>

<p>This is just a <a href="#">line</a> of text.</p>

<br><br>

<p>This is just a <span>line of text</span>.</p>

<br><br>

<figure><img src="demo.jpg" alt="text">
<figcaption>img description</figcaption>
</figure>

<p>This is just a line of text.</p>

<br><br>

<p>This is just a line of text.</p>

<table><tbody>
<tr><th>A</th><td>A value</td></tr>
<tr><th>B</th><td>B value</td></tr></tbody>
</table>

<br><br>

<p>This is just a line of text.</p>

</div>

最佳答案

这是用纯 JavaScript 实现此目的的一种方法。使用 findTextNodesFlat 替换 Each 函数。如果您想获取所有文本节点(与其深度无关),请改用 findTextNodesTree。然后使用wrapTextNodes函数包装文本节点。

// walks the child elements of a dom element and saves textnodes to the textNodes array
var findTextNodesFlat = function (node, textNodes) {
node = node.firstChild;
while(node) {
if (node.nodeType == Node.TEXT_NODE)
textNodes.push(node);

node = node.nextSibling;
}
};

// walks the dom element recursively and saves textnodes to the textNodes array
var findTextNodesTree = function (node, textNodes) {
if (node.nodeType == Node.TEXT_NODE)
textNodes.push(node);

node = node.firstChild;
while(node) {
findTextNodes(node, textNodes);
node = node.nextSibling;
}
};

// wraps the textNodes elements with <p></p>
var wrapTextNodes = function (textNodes) {
for(let node of textNodes) {
let parentNode = node.parentNode;
let wrapper = document.createElement('p');
parentNode.insertBefore(wrapper, node);
wrapper.appendChild(node);
}
};

var textNodes = [];
findTextNodesFlat(document.getElementsByClassName("content")[0], textNodes);
wrapTextNodes(textNodes);

关于javascript - 将 p 标签添加到无格式文本 - 纯 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60473574/

30 4 0