简体   繁体   中英

On IE document.getElementsByName won't work

I use this code:

<div name="1234">
   <img src="pic.gif" height="70" width="100" onMouseOver="clear('1234')">
</div> 

And:

function clear(element_name){
    document.getElementsByName(element_name)[0].innerHTML="";
}

It does work in Firefox and Opera, but doesn't work in IE 6.0 or IE 8.0, and probably not even in newer IE's.

What to do?

Well, the problem is this: IE understands document.getElementsByName(...)[0] as document.getElementById(...). So if you would define also an id for your element, the method document.getElementsByName(element_name)[0].innerHTML="" will surprisingly also work in IE!

But since you anyway need to define an id due to IE, and since an id must always start with a char first, you must use:

<div id="a234">
    <img src="pic.gif" height="70" width="100" onMouseOver="clear('a234')">
</div> 

And this command:

function clear(element_id){
    document.getElementById(element_id).innerHTML="";
}

Even more, document.getElementsByName(...)[0] is slower in Firefox: http://www.uize.com/tests/performance/getElementById-vs-getElementsByName.html

So the id definitely wins the race.

UPDATE:

Also important is the fact, that we can adress every id by #a234{...} in a CSS file. So we can define an own style for every id , and this makes the id even more powerful.

Using to get a DOM Element where the name attribute is not part of the W3C spec (eg, in the question, name doesn't exist for DIV element), IE doesn't get those elements. 获取DOM元素,其中name属性不是W3C规范的一部分(例如,在问题中,DIV元素不存在名称),IE不会获取这些元素。 FF does it.
Just to clarify: expando attribute or better known as custom attribute is what I am talking about attributes that are not part of the W3C spec.

Read: getElementsByName in IE7
Read: http://msdn.microsoft.com/en-us/library/ms536438(VS.85).aspx

So in conclusion:
Use when trying to get "Form Controls" (input, select, textarea) because they have name as an attribute according to the spec. ,因为它们根据规范将名称作为属性。
If the elements are not Form Controls, use getElementById instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM