PDA

View Full Version : DIV id situation


bbrantley
06-16-2008, 03:50 PM
I'm writing a simple page using XMLHTTPRequest to a CGI file on a server that spits out a data set when executed. The data set is formatted as follows:

name,value,name,value,name,value...

Once I receive the data I run the set through the following code to update any part of the website that has changed.

var mytext = http.responseText.split(",");
for (var i = 0; i < mytext.length; i = i + 2) {
document.getElementById(mytext[i]).innerHTML = mytext[i + 1];
}

This works fine as long as the 'name' portion has <div id='name'> associated with it. For example, if the data set is:

3,100,4,200

and there isn't a div id equal to 3, it hangs the program up. My page won't always have the same div id's, but could possibly receive a name in the data set that addresses a div id that is missing. Is there any kind of try/catch code associated with writing the innerHTML of a div?

Thank you for your time.

Horus_Kol
06-16-2008, 07:04 PM
little tip - use FF for testing javascript functionality, and get the FireBug plugin - you will get some good debug information on your JavaScript and Ajax requests...


so, anyway, the problem is that you are trying to access a property for an object that isn't there (at least, when there is no DIV with one of those IDs).

try this:

var mytext = http.responseText.split(",");
var element;

for (var i = 0; i < mytext.length; i = i + 2) {

element = document.getElementById(mytext[i]);

if (alert(typeof(element) == 'object') {
element.innerHTML = mytext[i + 1];
}

}

bbrantley
06-17-2008, 09:34 AM
Thanks for the reply. The code was not a copy paste fix, but I usually don't like those anyway :)

First off, the 'alert' was not needed as I don't want the user to know there is a problem per say.

Secondly, document.getElementById(div id) returns null is there isn't a id present. Knowing this, typeof(null) actually returns as an 'object' so it made it through the conditional if it wasn't a valid ID.

To fix this, compare the results of getElementById to not equal null and it works fine.

Also, I added an underscore to the variable name 'element' as it is a keyword in HTML.

var mytext = http.responseText.split(",");
var element_;

for (var i = 0; i < mytext.length; i = i + 2) {

element_ = document.getElementById(mytext[i]);

if (element_ != null) {
element_.innerHTML = mytext[i + 1];
}
}

Again thank you for the reply. Always helps to get a second opinion :)

Horus_Kol
06-17-2008, 07:00 PM
glad to have pointed you in the right direction... sorry my fix wasn't all there - but I tend to patch some answers on the fly...

what is odd is that my code worked for me in FF...