Using JavaScript to obtain data from HTML and XML Jul22 '06

JavaScript can interact with HTML and XML. When I first began working with AJAX, I often confused the method to obtain document data.

Using JavaScript to obtain HTML

In HTML, let’s say you have this code:

<p id="paragraph1">

    This is a paragraph

</p>

Using JavaScript to obtain the text "This is a paragraph", you’d write something like this:

var paragraph1 = document.getElementById("paragraph1").firstChild.nodeValue;

The text "This is a paragraph" is the first child of that <p> element. And nodeValue indicates the value of that node.

Using JavaScript to obtain XML

On the other hand, let’s say your XML looked like this:

<paragraph>This is a paragraph</paragraph>

The JavaScript to obtain "This is a paragraph" looks slightly different:

var paragraph1 = document.getElementsByTagName("paragraph")[0].firstChild.data;

We still use firstChild, but not nodeValue. Use data instead. Also, unless your XML has id attributes for the elements, you’ll have to use getElementsByTagName, as opposed to getElementById. The difference is that getElementsByTagName returns an array of all elements with that name. getElementById only returns a single element.

So, our JavaScript above assumes that paragraph1 is the first <paragraph> element in the XML document, hence the [0] after the getElementsByTagName:

getElementsByTagName("paragraph")[0]

Obviously, arrays in JavaScript start counting at 0, not 1.

Conclusion

This was one of the biggest differences I noticed when beginning AJAX work. Maybe someone else will stumble upon this entry, and save time.

Categories: HTML , JavaScript , XML

Add Feedback (view all)

Leave feedback

Feedback

Input format: The editor controls below will assist with Markdown syntax.

Status

Sub-status

Your info

matthom is published and produced by Matt Thommes - an independent publishing enthusiast, mobile blogger, content creator, informative writer, web developer from a suburb of Chicago. Never one to conform, Matt intends to promote the effect the web has on our lives, in an effort to intensify, instruct, and clarify all that is happening around us.

Contact Matt

Popular Pages

  1. Fast rounded corners in Photoshop (4151 recent visits)
  2. PHP – passing variables across pages (1558 recent visits)
  3. JavaScript set selected on load (1290 recent visits)
  4. Removing all child nodes from an element (882 recent visits)
  5. iPod songs out of order? (747 recent visits)
  6. Britney - Everytime piano tab (669 recent visits)
  7. Firefox 3 smart address bar: wildcard search (633 recent visits)
  8. MySQL LEFT JOIN syntax (543 recent visits)
  9. Breathe Me - Sia (508 recent visits)
  10. Tumblr: how blogging should be (403 recent visits)

Similar Entries

Stats

32 unique visits since August 2008

Syndicate

Advertisements