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 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

Similar Entries

Stats

198 unique visits since August 2008

Syndicate

Advertisements