<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()
和 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>
关于javascript - 在元素中查找未包裹在 html 标签中的文本,并用 <p> 包裹它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37506770/