One answer: Use the technique you mentioned, or any of the techniques the
others suggested. They will all work and are all fine to use.

Another answer: In code that is performance critical, you may want to bypass
all that and go right to the metal.

Each of your "item" elements contains a single text node, whose nodeValue is
the text. So, if you have an item refernece, item.childNodes[0].nodeValue is
the text value, or even better, item.firstChild.nodeValue.

A test you can run in Firebug:

  var $items = $('<items><item>Hello world!</item><item>Goodnight
moon!</item><items>');
  var item = $items.find('item')[1];
  // or any other code to get a single item, and then:
  alert( item.firstChild.nodeValue );  // "Goodnight moon!"

This will change if there are other elements nested inside an item, but you
can always poke around in Firebug to see what's what. Do a console.log of
the node you're interested in, and look at its properties.

-Mike

> I am using jquery to parse some xml.  I'm looking for the 
> best practice to access an elements text contents.
> 
> Let's say my xml looks like this:
> 
> <items>
>   <item>
>      Hello world!
>    </item>
>    <item>
>       Goodnight moon!
>    </item>
> <items>
> 
> I can get a wrapped set of the elements this way:
> $('items > item', xml)
> 
> And I can get the text of element 1 this way:
> $('items > item:eq(1)', xml).text()
> 
> But how do I get the contents once I am directly accessing 
> the element instead of the jquery object?
> 
> In other words I'd like to do something like this:
> $('items > item', xml)[1].text(), but since the element that's returned 
> from the array [] doesn't support text() how do I get it's contents?
> 
> I know I can wrap it in a second $ call, as in
> $($('items > item', xml)[1]).text() but that seems less than ideal.
> 
> Thanks!
> 

Reply via email to