jQuery在最深层获得文本节点同级 [英] jQuery get text node siblings at deepest level
问题描述
我有div
可能包含这样的文本:
I have div
s that may consist of text like this:
<div>
<p>
<span>My text <br /> Some more text</span>
</p>
</div>
或者像这样
<div>
<p> Here's a chunk of text </p>
</div>
或任何其他组合,但是最终级别中的文本可能会或可能不会被<br />
分隔. (是span
包含一个br
单个节点吗?还是两个同级兄弟姐妹?)
Or any other combination, but the final level will have text that may or may not be separated by <br />
. (Is a span
that contains a br
a single node? Or is it two siblings at the same level?)
在第一种情况下,我想要的最深层孩子的文字是:
In the first case, the text from the deepest children I want is:
My text
Some more text
第二个:
Here's a chunk of text
我的意思是-不论最深的层次,我都希望所有同级的兄弟姐妹.有帮助吗?
My point is - whatever the deepest level is, I want all siblings at that level. Any help?
我不能简单地使用$('p').text()
,因为这将仅返回文本,我需要对其进行编辑,然后返回到相同的兄弟姐妹,同时保留其样式.例如,如果我有
I cannot simply use $('p').text()
because this will return the text only, which I need to edit and then return to the same siblings, while retaining their styles. So for example if I have
<div>
<p>
<strong>
<span style='font-family:arial'> Here's some <br /> text</span>
</strong>
</p>
</div>
然后我做$('p').text()
,然后我会得到这里有一些文字".现在,当我在一个变量中操作此文本时,说changedText
(其中保留了<br />
),如何将其放回原点?我不能简单地做
And I do $('p').text()
then I'll just get "Here's some text". Now when I manipulate this text in a variable, say changedText
(with the <br />
retained within it), how can I put it back where it came from? I can't simply do
$('p').text(changedText);
,我也不能做$('p').html(changedText');
因为<strong>
和<span>
格式将丢失.因此,这就是为什么我只想通过选择div
中最深层次的文本节点(例如在$textNodes
中)来访问所有文本的原因.这样我就可以简单地执行$textNodes.text(changedText);
,同时保留文本节点的父级的结构和样式.
because the <strong>
and <span>
formatting will be lost. So that's why I just wanted to access all the text by selecting the deepest level of text nodes in a div
, let's say in a $textNodes
. So that I can simply do $textNodes.text(changedText);
while retaining the structure and style of the parents of the text nodes.
有可能吗?
推荐答案
可以使用.children()
直到到达最深的节点.我将其包装在jQuery函数中,如下所示.
You can use .children()
until you reach the deepest nodes. I wrapped it in a jQuery function as follows.
$.fn.deepest = function(){
var $level = this.first();
while (!!$level.children(":not(br)").length) {
$level = $level.children();
}
return $level;
};
console.log($("div").deepest());
//[ <span>My text <br> Some more text</span> ]
您可以使用.contents()
来获取文本节点并对其进行操作,或者使用.text()
.
You can use .contents()
to get the text nodes and manipulate them or .text()
.
这篇关于jQuery在最深层获得文本节点同级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!