Code won't work in IE

Hi,

The following code won’t work in IE. The alert reports x.length as zero. How can fix this?

function hideAll(name) {
	var x=document.getElementsByName(name);
	alert(x.length);
	for (var i=0;i<x.length;i++)
	{
		x[i].style.display='none';
	}
}

David

What is the HTML code that the JavaScript is interfacing with?

It’s just a bunch of div’s like so:

<a href="javascript:void(0)l" onclick="hideAll('toHide');">Hide All</a>
<div>Some content</div>
<div name="toHide">Sub content here</div>
<div>Some more content</div>
<div name="toHide">Sub content here</div>
<div>Some other content</div>
<div name="toHide">Sub content here</div>

David

Thanks.

Internet Explorer is broken when it comes to using getElementsByName
The name attribute should only be used to specify form fields that are to be submitted.

In the way you are attempting to use it, you will be much better served by using the class attribute instead.

Thanks for helping.

I can’t seem to find any native function for working on class attributes though. I kind of expected there to be a getElementByClass(), but alas there is not. How could I implement a function that performs similar function to mine but IE compatible?

David

There are a couple of ways.

Historically you would use these class handling functions which gives you hasClass(), addClass() and removeClass()

However, there is an improved technique nowdays by using querySelector() instead.


var elems = document.querySelector('toHide');