PDA

View Full Version : Arrays different in IE and others?


VIPStephan
05-23-2007, 05:05 PM
Well, as good as I am with XHTML and CSS as much do I have to learn in JavaScript programming. I’m just beginning to understand and modify the DOM and I ran into something that I couldn’t find a solution for after some extensive search.

I have this function:


if(document.getElementById && document.createElement) {
function addflags() {
var children = document.getElementById('pagelist').childNodes;
for(var i = 0; i < children.length; i++) {
children[0].className = 'bulgaria';
children[1].className = 'england';
children[2].className = 'italy';
children[3].className = 'sweden';
}
}
window.onload = addflags;
}


The XHTML is an unordered list with 4 list items and sub lists in those list items (plus links in each li) and I want to add a country flag (set as background image in the CSS) to the direct children of the ul (the first level list items).
Now I discovered that Firefox is only reacting to odd array numbers, i.e. children[1], 3, 5, and 7 (the even numbers have "no properties") while IE is applying the classes correctly(?) as intended above (0,1,2,3).
At which point did I go wrong?
Sorry if this is a real stupid question but I’m pretty new in this field and my researches didn’t bring any acceptable results.

Thanks.

BonRouge
05-23-2007, 05:10 PM
Can you show us the page?

glenngv
05-23-2007, 05:28 PM
Whitespaces are considered nodes in Firefox. Check for nodeType 1 for elements. Or you can clean the whitespace using this script (http://www.codingforums.com/showthread.php?t=7028).

VIPStephan
05-23-2007, 05:28 PM
OK, well, I’ve done it with conditional comments for now and used CSS 2 selectors for modern browsers but this is still bugging me. Here’s the page (http://www.vishnuprakash.com/stephan/freeway/?page_id=48) where I’ve done this. You can extract the relevant code to see it working (or not) in IE and FF.

glenngv
05-23-2007, 06:05 PM
We both posted at the same time so you might have missed my post above.

VIPStephan
05-23-2007, 06:30 PM
:)
Ah I see. So the line breaks before/after the tags are considered whitespaces, and thus count as nodes… pretty stupid behavior, eh?
Reminds me of the mysterious image gaps if you put them one on a line in the HTML code that newbies frequently stumble upon. :D

jkd
05-23-2007, 06:30 PM
Also, childNodes is not actually an array. Arrays are static, for one. The object returned by the childNodes property is a NodeList, which is live (dynamically reflects the state of the DOM). It just so happens that the ECMAScript bindings allow array-style [] access.