JQuery get text node siblings at deepest level

I have div

one which may consist of the following text:

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

      

Or like this

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

      

Or any other combination, but the last level will have text that may or may not be split <br />

. (Is that span

one that contains br

one node? Or is it two siblings on the same level?)

In the first case, the text from the deepest of my children:

My text
Some more text

      

In the second:

Here a chunk of text

      

My point is that whatever the deepest level, I want all brothers and sisters to be at that level. Any help?

Edit

I can't just use $('p').text()

because this will only return the text that I need to edit and then revert back to the same siblings while keeping their styles. So, for example, if I have

<div>
<p>
<strong>
<span style='font-family:arial'> Here some <br /> text</span>
</strong>
</p>
</div>

      

And I do $('p').text()

, then I just get "This is the text." Now that I am manipulating that text in a variable, say changedText

(with stored in it <br />

), how can I get it back to where it came from? I just can't do

$('p').text(changedText);

and I cannot do $('p').html(changedText');

because the format <strong>

and <span>

will be lost. So I just wanted to access all of the text by selecting the deepest level of text nodes in div

, say, in $textNodes

. So what I can do is just $textNodes.text(changedText);

keep the structure and style of the text node parents.

Is it possible?

0


source to share


3 answers


You can use .children()

until you reach the deepest knots. I wrapped it in a jQuery function like this.

$.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 and manage text nodes or .text()

.

+1


source


You can target BR

like a selector and replace it

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

      

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



If a potential problem with another is BR

higher in DIV

, use .last()

to isolate the latter, BR

or use filter()

to check if the latter is at its deepest level.

Providing some real world html examples that demonstrate the potential depth and possible tree structure would help. You can put them in the script demo and update it.

0


source


follow these steps: 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>

      

0


source







All Articles