Jump to content

Is this due to the compatibility issue on Firefox?


tinfanide

Recommended Posts

My script is working well in IE8 but not in Firefox 4.0.1 Portable.I've tested both getElementsByTagName and getElementById as some helps on the Internet said firefox might only load Id instead of TagName.I don't know much about the compatibility issue of JS in different browsers.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>JS: childNodes</title><script type="text/javascript">window.onload = function(){var li = document.getElementsByTagName("ul")[0].childNodes;var i;for (i=0; i<li.length; i++)	{		li[i].style.color = "red";	}var lia = document.getElementById("a");lia.style.color = "green";	}</script></head><body><ul><li>List 1</li><li>List 2</li><li>List 3</li><li>List 4</li></ul><ul><li id="a">ABCDEFG</li></ul></body></html>

Anyone who knows why?Thanks.

Link to comment
Share on other sites

that is because by using childNodes it would include text and spaces as well, and not just the LI tags.it would be better to use

<script type="text/javascript">/*<![CDATA[*//*---->*/window.onload = function(){var ul = document.getElementsByTagName("ul")[0];var li = ul.getElementsByTagName("li")var i;for (i=0; i<li.length; i++)	{//alert(li[i].nodeName) using this in original script would show childNode picking 'text' as in spaces		li[i].style.color = "red";	}var lia = document.getElementById("a");lia.style.color = "green";	}/*--*//*]]>*/</script>

Link to comment
Share on other sites

var li = document.getElementsByTagName("ul")[0].childNodes;var i;var list;for (i=0; i<li.length; i++)	{		list = li[i];		if(list.nodeType == 1){		list.style.color = "red";		}	}

I learnt nodeType from some of my other question posts and tried to use it here.If I define the list items as element nodes (as you guys said originally firefox counts every kind of nodes), it seems to work well in both of the browsers.Of course learning from your simple script, now I know I don't have to use childNodes in this case to style color the list items.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...