查找元素中未包含在 html 标签中的文本,并用 <p> 将其包裹起来. [英] Find text in element that is NOT wrapped in html tags and wrap it with <p>

查看:19
本文介绍了查找元素中未包含在 html 标签中的文本,并用 <p> 将其包裹起来.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我尝试了以下 jQuery 代码:

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

解决方案

使用 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 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 标签中的文本,并用 &lt;p&gt; 将其包裹起来.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆