在元素中查找未包含在html标记中的文本,并用<p>包装它

AJD*_*DEV 4 html javascript jquery word-wrap web

<div class="menu-content">
  <h3>Lorem Ipsum</h3>
  TEXT THAT NEEDS TO BE WRAPPED
  <ul>
    <li>List Item 1</li>
  </ul>
</div>
Run Code Online (Sandbox Code Playgroud)

我得到了上面的代码(它自动生成,所以我不能手动包装文本),我需要过滤".menu-content"的内容,找到没有包装在html标签中的文本,然后换行ap标签中的文本.

我尝试了以下jQuery代码:

$('.menu-content').find(':not(h3, ul)').wrap('<p></p>');
Run Code Online (Sandbox Code Playgroud)

Pra*_*lan 6

使用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
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)