在元素中查找未包含在html标记中的文本,并用< p> [英] Find text in element that is NOT wrapped in html tags and wrap it with <p>
本文介绍了在元素中查找未包含在html标记中的文本,并用< p>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
< div class =menu-content>
< h3> Lorem Ipsum< / h3>
需要包裹的文本
< ul>
< li>清单项目1< / li>
< / ul>
< / div>
我得到了上面的代码(它会自动生成,因此我无法手动包装文本),我需要过滤.menu-content的内容并找到未包含在html标签中的文本,然后将该文本包装在ap标签中。
我尝试了以下jQuery代码:
$('。menu-content')。find(':not(h3,ul ) ')包裹(' < p为H.;< / p为H.');
解决方案
使用 contents()
和 filter()
获取文本节点
$('。menu-content').contents()//获取包含文本和注释的所有子节点.filter (function(){//过滤非空的文本节点返回this.nodeType === 3&& $ .trim(this.textContent).length})。wrap('< / p>) ; //使用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>需要包装的文字< ul> < li>列表项目1< / li> < / div>
<div class="menu-content">
<h3>Lorem Ipsum</h3>
TEXT THAT NEEDS TO BE WRAPPED
<ul>
<li>List Item 1</li>
</ul>
</div>
I got the code above (it gets generated automatically so I can't manually wrap the text), I need to filter through the content of ".menu-content" and find the text that is not wrapped in a html tags and then wrap that text in a p tag.
I tried the following jQuery code:
$('.menu-content').find(':not(h3, ul)').wrap('<p></p>');
解决方案
Use contents()
and filter()
to get text node
$('.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>
这篇关于在元素中查找未包含在html标记中的文本,并用< p>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文