selectSingleNode works but not selectNodes

Troy picture Troy · Jun 25, 2010 · Viewed 22.5k times · Source

Javascript:

var req=xmlDoc.responseXML.selectSingleNode("//title");
alert(req.text);

as expected, returns the text of the first "title" node.

but this

var req=xmlDoc.responseXML.selectNodes("//title");
alert(req.text);

returns "undefined." The following:

var req=xmlDoc.responseXML.selectNodes("//title").length;
alert(req);

returns "2." I don't get it. Maybe when I selectNodes it isn't getting the text node inside the title. That's my guess for now...here is the xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE catalog SYSTEM "catalog.dtd">
<catalog>
<decal>
<company>Victor</company>
<title>Wood Horn Blue Background</title>
<image>
<url>victor01.jpg</url>
<width>60</width>
<height>60</height>
<name>Wood Horn Blue Background</name>
<link></link>
</image>
<price>$15.00</price>
<instock>In Stock</instock>
<notes>no extra info</notes>
</decal>
<decal>
<company>Victor</company>
<title>Wood Horn without Black Ring</title>
<image>
<url>victor02.jpg</url>
<width>60</width>
<height>60</height>
<name>Wood Horn Without Black Ring</name>
<link></link>
</image>
<price>$15.00</price>
<instock>In Stock</instock>
<notes>no extra info</notes>
</decal>
</catalog>

thanks

Answer

SLaks picture SLaks · Jun 25, 2010

selectNodes returns an array.

Therefore, when you write var req=xmlDoc.responseXML.selectNodes("//title"), the req variable holds an array of elements.
Since arrays do not have a text property, you're getting undefined.

Instead, you can writereq[0].text to get the text of the first element in the array.