Nope, that line looks good. The problem is that the name attribute is non-standard for the div element. So, for example, say we do this:
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
onload = function(){alert(document.getElementsByName('stories').length);};
</script>
</head>
<body>
<div name="stories" id="myvar1"></div>
</body>
</html>
Firefox alerts:
1
more or less as expected, but as mentioned above this is actually an error of sorts. IE 'gets it right' in this case, by ignoring the non-standard (technically invalid) name attribute, it alerts:
0
The name attribute is valid for these tags:
- a
- img
- form
- input
- textarea
- area (perhaps)
Maybe a few others. Generally, for what you are trying to do, class is used in conjunction with document.getElementsByClassName, but IE has no document.getElementsByClassName. So this (or something like it) is often done:
Code:
window.onload = function initAll() {
// this function closes all the contained elements within the main content, on onload
var argument = document.getElementsByTagName("div").length;
// loop through each element with an identical name attribute to store the instances
for (var i=0, c=0;i<argument;i++) {
if(argument[i].className === 'stories'){
document.getElementById('myvar'+[++c]).style.display="none";
}
}
};
with markup like:
Code:
<div class="stories" id="myvar1">
<p class="news">Headlines</p>
But this is less than ideal because an element may have more than one class. If you keep things simple though, it will be fine.
Speaking of simple though, consider the implications of this:
Code:
window.onload = function initAll() {
// this function closes all the contained elements within the main content, on onload
var argument = document.getElementsByTagName("div").length;
// loop through each element with an identical name attribute to store the instances
for (var i=0;i<argument;i++) {
if(argument[i].className === 'stories'){
argument[i].style.display="none";
}
}
};
A final note for now, although this construct:
Code:
window.onload = function initAll() {
is to be preferred for a number of reasons, it can cause problems in some cases, better to just do:
Code:
window.onload = function() {
Or even better as it incorporates the advatages without causing problems, define the initAll() function separately and invoke it directly:
Code:
function initAll(){
whatever;
}
onload = initAll;
Bookmarks