Reputation: 35
I'm new to DOM. I want to get the text of the first node with tag title in this xml file http://www.w3schools.com/xml/books.xml , which is Everyday Italian. The answer should be this:
var x = xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
From what I see,
xmlDoc.getElementsByTagName("title")[0]
Gets the first title node from an array consisting all nodes of title tag. And if I want to get the text of that node, Shouldn't it be like this?
xmlDoc.getElementsByTagName("title")[0].nodeValue
Why does it have something to do with childNodes ? And what type is this?
xmlDoc.getElementsByTagName("title")[0].childNodes[0]
Upvotes: 1
Views: 8829
Reputation: 2728
var x = xmlDoc.getElementsByTagName("title")[0].childNodes[0].textContent;
I tried innerHTML
and childNodes[0]
but neither worked - only the above worked for me.
Source: Node.textContent - Mozilla WebDocs
Upvotes: 1
Reputation: 75
From http://www.w3schools.com/xml/dom_nodes_get.asp -
'In the DOM, everything is a node. Element nodes do not have a text value. The text value of an element node is stored in a child node. This node is called a text node.'
xmlDoc.getElementsByTagName("title")[0] // first title element node
So, .childNodes[0] is required to access its text node which is where the text value is stored
Upvotes: 0