jQuery选择并包装textNode [英] jQuery select and wrap textNode
问题描述
我想选择div元素中的文本并用< b>
标记包装它。 < b>
标记应仅包装到div内的文本而不是文本内的子元素,例如< p> $ c此示例中为$ c>标记。
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);
推荐答案
您可以使用 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屋!