1

Is it possible to select the value of a tag which is not inside another nested tag?

For example in the following code I want to get ' Text I want to select' from $('#example').

<td id="example">
    <a> Text I don't want to select</a>
    <span> Other text I don't want to select</span>
    Text I want to select
    <anyOtherTag> Other text I don't want to select</anyOtherTag>
</td>

Thanks.

Javi
  • 19,387
  • 30
  • 102
  • 135
  • jQuery doesn't have a helper function for this. Here is a great thread on the issue (How do I select text nodes w/ jQuery). http://stackoverflow.com/questions/298750/how-do-i-select-text-nodes-with-jquery – John Himmelman Dec 15 '10 at 19:04

1 Answers1

3

You can use .contents() and .filter() down to text node types (nodeType == 3), like this:

var text = $("#example").contents().filter(function() { 
              return this.nodeType == 3; 
           }).text();
alert($.trim(text));

You can try it out here. since .text() gets all text nodes, including the other whitespace, you probably want to $.trim() (since IE<9 doesn't have String.trim()) the result like I have above.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • Thanks good Idea. The only problem is that I don't get it working in my real example. Indeed my table is used with jquery plugin datatables and jeditable so when the user clicks on a table I want to get that information. I've logged my variables and I'm getting with $(this) the correct td, but when I do $(this).contents() it is empty. May it be because I'm using datatables plugin? – Javi Dec 15 '10 at 19:20
  • @Javi - it all depends on your context, try a `console.log(this)` and see where you are when it happens – Nick Craver Dec 15 '10 at 19:22