jQuery选择并包装textNode [英] jQuery select and wrap textNode

查看:107
本文介绍了jQuery选择并包装textNode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想选择div元素中的文本并用< b> 标记包装它。 < b> 标记应仅包装到div内的文本而不是文本内的子元素,例如< p> 标记。

I want to select the text inside the div element and wrap it with a <b> tag. The <b> tag should only wrap to text inside div and not text inside a child element such as the <p> tag in this example.

<div>Testing
    <p>Some more text inside p</p>
    <p>asdasdasdasdasde p</p>
    Test
</div>

我可以选择< p> 使用以下文本,但我无法对 div 执行相同的操作。我只想要 div 的文本而不是 p 。对于这种情况,它应该选择并包装测试测试

I'm able to select the <p> text using the following, but I'm not able to do the same for div. I only want the text of div and not p. For this case it should select and wrap Testing and Test.

var x = $('p')[0].textContent; // this is not working for div.
console.log(x);

JSFiddle

推荐答案

您可以使用 contents ,并按节点类型过滤(3表示文本节点):

You can use contents, and filter by node type (3 is for text node):

$('div').contents()
        .filter(function(){return this.nodeType === 3})
        .wrap('<b />');

示例: http ://jsfiddle.net/nJqKq/8

另请参阅:节点类型,位于MDC

See also: Node Types, at MDC

这篇关于jQuery选择并包装textNode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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