PDA

View Full Version : reading node values with javascript


homerUK
05-29-2007, 04:55 PM
hey,

this is probably an easy one, but ive only just started out using XML data. i'm for now, using a test tree of data but cannot access it using javascript... here's the data... (from PHP)


<ajax-reponse>
<response type="object">

<row>
<a>15</a>
<b>78</b>
<c>1</c>
<d>2</d>
<e>3</e>
<f>4</f>
</row>

<row>
<a>12</a>
<b>65</b>
<c>31</c>
<d>26</d>
<e>83</e>
<f>40</f>
</row>


</response>
</ajax-reponse>


the Javascript I'm using is this


var xmlDoc = t.responseXML; //coming from an ajax response
var _post = xmlDoc.getElementsByTagName("row");
for (x=0;x<_post.length;x++) {
alert(document.getElementByTagName("row").firstChild.nodeValue);
}


I've read up on the XML and from what i understand, the above code should be producting the value of the first tag in each "row" ??

not sure where I'm going wrong!

Bill Posters
05-29-2007, 05:07 PM
Could be a whitespace issue.

Whitespace (nodeType == 3) is treated as a node by some browsers.
You'll either need to keep looping through the childNodes until you find an element node (nodeType == 1) - or remove the whitespace from your markup.

See: http://developer.mozilla.org/en/docs/DOM:element.nodeType

homerUK
05-29-2007, 05:14 PM
thanks for the reply.. ive removed all the white space, still nothing...
..i just get "undefined" for this..

what would be the code to alert() all the nodetypes... ive tried

alert(xmlDoc.getElementsByTagName("row").nodeType);

which didn't work...

homerUK
05-29-2007, 05:33 PM
I've managed to access the nodes now, using

xmlDoc.getElementsByTagName("field")[0].childNodes[0].nodeValue;

:)

Bill Posters
05-29-2007, 07:10 PM
thanks for the reply.. ive removed all the white space, still nothing...
..i just get "undefined" for this..

what would be the code to alert() all the nodetypes... ive tried

alert(xmlDoc.getElementsByTagName("row").nodeType);

which didn't work...
Fwiw…

The reason you were getting undefined is because you're referencing an array object /html collection (which doesn't have a nodeType property) - i.e. getElementsByTagName("row").

For code maintainance purposes, you might find it preferable to keep the whitespace (i.e. formatting) in there.
If so, you can still get to the first element-type child by doing a little checking and shifting…

e.g.
var trgtEl = document.getElementsByTagName('row')[0].childNodes[0];
if (trgtEl.nodeType != 1) trgtEl = trgtEl.parentNode.childNodes[1];
alert(trgtEl.childNodes[0].nodeValue);

// or

var trgtEl = document.getElementsByTagName('row')[0].childNodes[0];
if (trgtEl.nodeType != 1) trgtEl = trgtEl.nextSibling;
alert(trgtEl.childNodes[0].nodeValue);

:)