Dom对象的方法应用一getElementById技巧、getElementsByName() IE,firefox兼容

在document对象中有以下三个方法,对于程序员来说,真可谓无人不知,无人不晓,他们分别是:

1.getElementById()                  返回对拥有指定 id 的第一个对象的引用。

2.getElementsByName()           返回带有指定名称的对象集合。

3.getElementsByTagName()     返回带有指定标签名的对象集合。

这三个方法尤其是:getElementById() 的使用频率极高,故通过以下方法简化其调用:

<!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>test</title>
    <script type="text/javascript">
       function $(s){
        return document.getElementById(s);
    }
    function test3(){
        alert($("userName").value);
    }
    </script>
</head>
<body>
<input type="text" id="userName" value="你好!" /><br /> 
<input type="button" value=Test3 onclick="test3();"><br> 
</p>
</body>
</html>

一个$()函数的定义大大简化了操作,代码变得多优雅啊 oh yeah!

最后要注意getElementsByName() 在IE下的一个BUG:

在IE中:      document.GetElementsByName(“jack”); 会返回name,id 属性值为jack的元素数组(如果只设置name并不能获得对象)。

但在FF中只会返回只会返回name 属性值为jack的元素数组。

<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
    <title>Test</title>
<script language="javascript">
function func() {
    var channelset = document.getElementsByName("a");
    for (i = 0; i < channelset.length; i++) {
         if (channelset[i].style.display == 'none') {
             channelset[i].style.display = 'block';
         } else {
             channelset[i].style.display = 'none';
         }
    }
}
</script>
</head>
<body>
    <p onClick="func();">Menu Bar</p>
    <p name="a" style="display:none">item1</p>
    <p name="a" style="display:none">item2</p>
</body>
</html>

以上代码在FF正常,但在IE就有问题了,兼容ie的方法如下: 在使用name属性的地方须加上id属性。

<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
    <title>Test</title>
<script language="javascript">
function func() {
    var channelset = document.getElementsByName("a");
    for (i = 0; i < channelset.length; i++) {
         if (channelset[i].style.display == 'none') {
             channelset[i].style.display = 'block';
         } else {
             channelset[i].style.display = 'none';
         }
    }
}
</script>
</head>
<body>
    <p onClick="func();">Menu Bar</p>
    <p name="a" style="display:none" id="a">item1</p>
    <p name="a" style="display:none" id="a">item2</p>
</body>
</html>
原文地址:https://www.cnblogs.com/hubing/p/3245520.html