问题
<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>');
回答1:
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>
来源:https://stackoverflow.com/questions/37506770/find-text-in-element-that-is-not-wrapped-in-html-tags-and-wrap-it-with-p