Zongyang
Zongyang

Reputation: 35

Get text node value in DOM

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

Answers (3)

Yvonne Aburrow
Yvonne Aburrow

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

usr56777
usr56777

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

ne1410s
ne1410s

Reputation: 7082

The text content behaves as a childNode in this case. It may be that a line break or other character is causing this to happen. (See here, for example)

Either way you can access the content as follows:

xmlDoc.getElementsByTagName("title")[0].innerHTML

Upvotes: 1

Related Questions