Find text in element that is NOT wrapped in html tags and wrap it with <p>

空扰寡人 提交于 2019-12-01 05:54:38

问题


<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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!