使用<p>标记包装内容,该标记不包含在jquery </header>中的</p> <header>标记

时间:2014-04-02 13:41:54

标签: javascript jquery html

在编辑器中,如果用户键入内容并希望用“p”标记包装内容,而该标记在jquery keyup事件中没有用标题标记包装。

例如

<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>

3 个答案:

答案 0 :(得分:1)

如果您的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>

然后您可以使用 .contents() .filter() 来完成您的任务:

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

<强> Fiddle Demo

答案 1 :(得分:1)

尝试否定: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/>');
    }
});

jsFiddle

:header

.wrap()

答案 2 :(得分:0)

以前的帖子被盗:Finding untagged elements with 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
 }
}
相关问题