我有以下HTML代码。我想找到并替换没有HTML标签的文本,并使用jQuery将其包装在p
元素中。有没有办法达到我的目标?
<div class="col span_12_of_12 firstDiv">
<h2>My tasks</h2>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr
<ul>
<li>Lorem ipsum dolor sit</li>
<li>Lorem ipsum dolor sit</li>
<li>Lorem ipsum dolor sit</li>
<li>Lorem ipsum dolor sit</li>
</ul>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr
</div>
答案 0 :(得分:7)
要实现此目的,您需要找到子textNodes并将其包装在<p>
标记中。为此,您可以使用contents()
和filter()
,然后使用wrap()
,如下所示:
$('.col').contents().filter(function() {
return this.nodeType == 3 && this.textContent.trim();
}).wrap('<p />');
p { border: 1px solid #C00; } /* only used to make the output obvious */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col span_12_of_12 firstDiv">
<h2>My tasks</h2>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr
<ul>
<li>Lorem ipsum dolor sit</li>
<li>Lorem ipsum dolor sit</li>
<li>Lorem ipsum dolor sit</li>
<li>Lorem ipsum dolor sit</li>
</ul>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr
</div>