Richard Garfield Richard Garfield - 5 days ago 5
HTML Question

How to read attribute of child element with DOMParser in JavaScript

I have this xml

<zone name="main">
<card number="4" price="0" name="Urza's Tower"/>
<card number="4" price="0" name="Urza's Power Plant"/>
<card number="4" price="0" name="Urza's Mine"/>
<card number="4" price="0" name="Urza's Avenger"/>
<card number="1" price="0" name="Urza's Miter"/>
<card number="4" price="0" name="Howling Mine"/>


And I'd like to read the name attributes. I try this but it doesn't work:

var cards = xmlDoc.getElementsByTagName("zone")[0].childNodes;
for (var i = 0; i < cards.length; i++) {
console.log(cards[i].getAttribute("name"));
}


When I view
cards[i]
in the debugger it shows all the attributes. I just can't seem to access them...

Thanks!

Answer

The code in the question is using .childNodes so it’s not getting just the card element nodes but also the text nodes between the card elements.

To get just the card element nodes, use .children instead, like this:

 var cards = xmlDoc.getElementsByTagName("zone")[0].children;
      for (var i = 0; i < cards.length; i++) {
        console.log(cards[i].getAttribute("name"));
      }
Comments