admin管理员组文章数量:1245744
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?
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?
Share Improve this question edited Feb 4, 2013 at 6:31 Marcus asked Jan 29, 2013 at 4:29 MarcusMarcus 1,2322 gold badges14 silver badges23 bronze badges2 Answers
Reset to default 6Well, 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 mand:
function clear(element_id){
document.getElementById(element_id).innerHTML="";
}
Even more, document.getElementsByName(...)[0] is slower in Firefox: http://www.uize./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 getElementsByName 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. 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./en-us/library/ms536438(VS.85).aspx
So in conclusion:
Use getElementsByName 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.
本文标签: javascriptOn IE documentgetElementsByName won39t workStack Overflow
版权声明:本文标题:javascript - On IE document.getElementsByName won't work - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740204090a2240744.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论