使用 <p> 标记包装内容,该标记在 jQuery 中不使用 <header> 标记包装

wrap the content with <p> tag which is not wrap with <header> tag in jquery

本文关键字:包装 header jQuery 使用      更新时间:2023-09-26

在编辑器中,如果用户键入内容并希望使用"p"标签包装内容,该标签在jquery键控事件中不与标题标签包装。

例如

<h1>Header1</h1>
Test content Test content Test content 
<h3>Header3</h3>
<h2>Header2</h2>
New content New content New content
<br/>
<br/>
<h4>Header4</h4>

结果 html:

<h1>Header1</h1>
<p>Test content Test content Test content </p>
<h3>Header3</h3>
<h2>Header2</h2>
<p>New content New content New content</p>
<p></p>
<p></p>
<h4>Header4</h4>
例如,

如果您的 HTML 标记包装在<div>中:

<div id="content">
    <h1>Header1</h1>
    Test content Test content Test content       
    <h3>Header3</h3>
    <h2>Header2</h2>
    New content New content New content
    <br/>
    <br/>
    <h4>Header4</h4>
</div>

然后你可以使用 .content() 和 .filter() 来完成你的任务:

$('#content').contents().filter(function() {
    return this.nodeType === 3 && $.trim(this.nodeValue).length;
}).wrap('<p />');

小提琴演示

尝试否定:header选择器,然后使用 .wrap() 将未换行的文本节点包装在段落标签中。

var textNodes = $('body').not(':header,p *').contents().filter(function () {
    if(this.nodeType === 3 && this.textContent.trim() != "")
        return true;
});
textNodes.each(function () {
    if ($(this).parent().is('body')) {
        $(this).wrap('<p/>');
    }
});

js小提琴

:页眉

.wrap()

从上一篇文章中窃取: 使用 javascript 查找未标记的元素

var nodes = document.getElementsByTagName('body').childNodes
for (i=0; i < nodes.length; i++)
{
 if(nodes.childNode[i].nodeType == 3)
 {
 //THIS NODE IS A TEXT NODE OF THE BODY ELEMENT
 //DO WHAT YOU NEED WITH IT
 }
}