在元素中查找未包裹在 html 标签中的文本,并将其包裹在 <p> 中
Find text in element that is NOT wrapped in html tags and wrap it with <p>
<div class="menu-content">
<h3>Lorem Ipsum</h3>
TEXT THAT NEEDS TO BE WRAPPED
<ul>
<li>List Item 1</li>
</ul>
</div>
我得到了上面的代码(它是自动生成的,所以我不能手动换行),我需要过滤“.menu-content”的内容,找到没有换行的文本html 个标签,然后将该文本包装在 p 标签中。
我尝试了以下 jQuery 代码:
$('.menu-content').find(':not(h3, ul)').wrap('<p></p>');
使用contents()
and filter()
获取文本节点
$('.menu-content')
.contents() // get all child node including text and comment
.filter(function() { // filter the text node which is not empty
return this.nodeType === 3 && $.trim(this.textContent).length
}).wrap('</p>'); // wrap filtered element with p
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu-content">
<h3>Lorem Ipsum</h3>
TEXT THAT NEEDS TO BE WRAPPED
<ul>
<li>List Item 1</li>
</ul>
</div>
<div class="menu-content">
<h3>Lorem Ipsum</h3>
TEXT THAT NEEDS TO BE WRAPPED
<ul>
<li>List Item 1</li>
</ul>
</div>
我得到了上面的代码(它是自动生成的,所以我不能手动换行),我需要过滤“.menu-content”的内容,找到没有换行的文本html 个标签,然后将该文本包装在 p 标签中。
我尝试了以下 jQuery 代码:
$('.menu-content').find(':not(h3, ul)').wrap('<p></p>');
使用contents()
and filter()
获取文本节点
$('.menu-content')
.contents() // get all child node including text and comment
.filter(function() { // filter the text node which is not empty
return this.nodeType === 3 && $.trim(this.textContent).length
}).wrap('</p>'); // wrap filtered element with p
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu-content">
<h3>Lorem Ipsum</h3>
TEXT THAT NEEDS TO BE WRAPPED
<ul>
<li>List Item 1</li>
</ul>
</div>