Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding text node

Is there a clever jQuery selector for selecting a text node like this:

<div><input type="text">one <span>two</span> three</div>

I would like to get three from the markup above and wrap it in a strong tag like this:

<div><input type="text">one <span>two</span> <strong>three</strong></div>
like image 947
David Hellsing Avatar asked Dec 17 '22 03:12

David Hellsing


1 Answers

Here is how to select text nodes using jQuery:

var x = $('div') 
  .contents() 
  .filter(function() { 
    return this.nodeType == 3;
    //return this.nodeType == Node.TEXT_NODE;  this works unless using IE 7
  }); 

In your example x will then contain 'one' at index 0 and 'three' at index 1. Like Keith Rousseau said, you can't really just grab that text, but if you know it will be last you can get it like this:

var elemThree = x[x.length-1];

You can also add the strong tag like this:

$(x[x.length-1]).wrap("<strong></strong>");

This questions describes selecting text nodes with jQuery (my first code snippet).

like image 109
rosscj2533 Avatar answered Jan 02 '23 13:01

rosscj2533