jQuery get text node siblings at deepest level

前提是你 提交于 2019-12-11 18:36:27

问题


I have divs that may consist of text like this:

<div>
<p>
<span>My text <br /> Some more text</span>
</p>
</div>

Or like this

<div>
<p> Here's a chunk of text </p>
</div>

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

In the second:

Here's a chunk of text

My point is - whatever the deepest level is, I want all siblings at that level. Any help?

Edit

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>

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); and neither can I do $('p').html(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.

Is that possible?


回答1:


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>​ ] 

You can use .contents() to get the text nodes and manipulate them or .text().




回答2:


do something like this: http://jsfiddle.net/hWkkJ/2/

jquery:

$(function(){
  $('.append').append($('p').html()); 
});

html:

<div>
<p>
<span>My text <br /> Some more text</span>
</p>
</div>

<div class="append"></div>



回答3:


You could just target the BR as selector and replace it

$('p br').replaceWith('\n');

DEMO: http://jsfiddle.net/fhnHR/1/

If potential problem with other BR higher in the DIV use .last() to isolate last BR, or use filter() to check if the last one is in the deepest level.

Providing some more real world html examples that demonstrate potential depth and possible tree structure would help. You could place them in fiddle demo and update it



来源:https://stackoverflow.com/questions/14425152/jquery-get-text-node-siblings-at-deepest-level

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!