0

I've been for numerous tutorials and I still can't seem to get this right.

I have the following XML document

<?xml version="1.0" encoding="UTF-8"?>

<bookstore>

  <book category="COOKING">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>

  <book category="CHILDREN">
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>

  <book category="WEB">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>

</bookstore>

I also have the folowing javascript in my HTML

if (window.XMLHttpRequest)
  {
  xhttp=new XMLHttpRequest();
  }
else // for IE 5/6
  {
  xhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xhttp.open("GET","book.xml",false);
xhttp.send();
xmlDoc=xhttp.responseXML;

alert(xmlDoc.getElementsByTagName("title").nodeValue);

I want to be able to alert a specific title ( or all title if possible ).

How is this possible?

6
  • What do you get if you log xmlDoc to the console? Commented Oct 28, 2013 at 13:31
  • getElementsByTagName returns a node list, you can not use nodeValue on a list. Commented Oct 28, 2013 at 13:32
  • As epascarello said, you will have to iterate through the NodeList returned by getElementsByTagName to look at individual Nodes. Commented Oct 28, 2013 at 13:33
  • So how can I get just the first "title" and alert it? Commented Oct 28, 2013 at 13:34
  • Loop through the nodes and filter it down to your title Commented Oct 28, 2013 at 13:35

1 Answer 1

1

So how can I get just the first "title" and alert it?

Assuming xmlDoc,

var titles = xmlDoc.getElementsByTagName("title"); // NodeList
if (titles[0])                    // if there is an item in index 0
    alert(titles[0].textContent); // alert it's textContent
else                              // otherwise
    alert('Error: no titles');    // some error message
Sign up to request clarification or add additional context in comments.

2 Comments

@craig sorry, assumed nodeValue was the property you wanted, try with textContent instead (edited).
Im assuming document.getElementById('booktitle1').innerHTML=(titles[0].textContent); should work?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.