Suppose I get the following XML structure:
<root>
<item>
<item1>text1</item1>
<item2>text2</item2>
more text here
</item>
</root>
"more text here" is a text node that is at the same level as the other data nodes in the hierarchy but it does not seem to be accessible.
Is there a way of extracting the text node shown above using jQuery functions?
I came up with the same solution:
var xml = $("<root><item1>text1</item1><item2>text2</item2>more text here</root>");
alert($(xml).contents().empty().end().text());
Use the contents() function. For example, if you have an XML fragment like:
var root = $('<root><item1>text1</item1><item2>text2</item2>more text here</root>');
Then you can get at the text via:
var txt = root.contents()[2]
That is assuming that the text node is always the 3rd child of <root>. Otherwise, if you do not know the position, or may have a node that contains multiple text nodes, you should collect all of the text nodes by filtering:
var textList = root.contents().filter(function() { return this.nodeType == 3; });
This returns an array of text nodes that are found in the XML fragment. To get at the strings in the list, just access the array slice:
var txt = textList[0];
So the solution I came up with is to delete the item1 and item2 nodes leaving only the text:
$(responseXML).find('item').each(function(){
var item1_text = $(this).find('item1').text();
var item2_text = $(this).find('item2').text();
$(this).contents().empty(); //removes the other nodes
var extra_text = $(this).text();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With