0

Sorry for the vague title. Here's an example of what I'd like to do.

<book>
  The Lord of the Rings
  <author>JRR Tolkien</author>
</book>

$xml.find("book").each(function()
{
  $(this).text();
});

$(this).text(); returns not only "The Lord of the Rings" but also ... and any other nodes inside . I'm looking for a consistant way to return only "The Lord of the Rings" or whatever information i have in there.

Hamer
  • 1,354
  • 1
  • 21
  • 34

3 Answers3

3

You need to use contents() to get all nodes and then .filter() it to get rid of any nodes that are not text nodes:

$xml.find("book").contents().filter(function() {
    return this.nodeType == Node.TEXT_NODE;
}).each(function() {
    // $(this).text();
});

Source

If the code needs to work in IE7, too, you'll have to replace Node.TEXT_NODE with 3.

Community
  • 1
  • 1
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
2

Likely that text will always preceed tag so you can grab first node of contents also

$(xml).find('book').each(function(){
   var text=$(this).contents().eq(0).text();
});

DEMO: http://jsfiddle.net/nS5bj/

charlietfl
  • 170,828
  • 13
  • 121
  • 150
1

You can clone the element and remove that clone's children, leaving the bare text:

$xml.find("book").each(function()
{
    var title = $(this).clone().children().remove().end().text();
});

The use of .end here is key, as it terminates the .remove operation (removing all child tags), leaving the leftover text.

JSFiddle

Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144