document.getElementById/Name/TagName区别

参考:http://blog.csdn.net/djf_1985/article/details/3548004

http://blog.csdn.net/binzai325/article/details/6777516

http://zhidao.baidu.com/question/199450007.html

http://kaixin322.i.sohu.com/blog/view/87917643.htm

document.getElementById/Name/TagName区别

 

document.getElementsByName() 是根据控件名称(name属性)获取这个控件对象,因为控件名称可以相同,返回的是一个对象数组
document.getElementById() 是根据控件ID获取这个控件对象,因为控件ID唯一,返回的是一个对象
document.documentElement.getElementsByTagName() 是根据控件TAG(type属性)获取这个控件对象,返回的是一个对象数组

eg:
HTML中有控件如下:
<input id="File1" type="file" name="up1"/>
<input id="File2" type="file" name="up1" />
<input id="File3" type="file" name="up2" />
则:
document.getElementsByName("up1") 取得的是两个控件,可以用document.getElementsByName("up1")[0] 取得的是第一个控件。
document.getElementById("up1")取得的是第一个控件,
document.documentElement.getElementsByTagName("input") 取得的是这三个控件,可以用document.documentElement.getElementsByTagName("input")[0] 取得的是第一个控件。

 

 

document.getElementById
1、getElementById
作用:一般页面里ID是唯一的,用于准备定位一个元素
语法: document.getElementById(id)
参数:id :必选项为字符串(String)
返回值:对象; 返回相同id对象中的第一个,按在页面中出现的次序,如果无符合条件的对象,则返回 null
example:
document.getElementById("id1").value;
2、getElementsByName
作用:按元素的名称查找,返回一个同名元素的数组
语法: document.getElementsByName(name)
参数:name :必选项为字符串(String)
返回值:数组对象; 如果无符合条件的对象,则返回空数组,按在页面中出现的次序
注意:返回数组值为value属性的值,
如果某标签无value属性,当你添加上value属性并赋值后,getElementsByName也能取到其值,
当未对value属性赋值时, getElementsByName返回数组值将是undefined ,
但仍能获得相同name标签的个数document.getElementsByName(name).length
当未设置name属性时document.getElementsByName仍能使用,它将根据你id取得value属性的值
example:
document.getElementsByName("name1")[0].value;
document.getElementsByName("name1")[1].value;
<span id='CBylawIndexName' class='normalNode' value='all' >全部</span>"
<span id='CBylawIndexName' class='normalNode' value='ALL' >全部</span>"
span标签其实没有name和value属性
但document.getElementsByName("CBylawIndexName")仍将取得value的值
3、getElementsByTagName
作用:按HTML标签名查询,返回一个相同标签元素的数组
语法: object.getElementsByTagName(tagname) object可以是document或event.srcElement.parentElement等
参数:tagname:必选项为字符串(String),根据HTML标签检索。
返回值:数组对象; 如果无符合条件的对象,则返回空数组,按在页面中出现的次序
example:
document.getElementsByTagName("p")[0].childNodes[0].nodeValue;
document.getElementsByTagName("p")[1].childNodes[0].nodeValue

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值