原文地址:http://blog.csdn.net/binzai325/article/details/6777516 内容有添改
JS获取DOM的不同方式
1、querySelector
作用:根据id、class、tagName等任意选择符获取元素
语法: document.querySelector('#id')、document.querySelector('.class')形式
参数:类似jQuery
返回值:有一个元素返回该元素,有多个元素返回元素数组。
2、表单内不同数据类型取值示例
input : document.querySelector('#id').value
select : document.querySelector('#id').value
textarea : document.querySelector('#id').value
3、getElementById
作用:一般页面里ID是唯一的,用于准备定位一个元素
语法: document.getElementById(id)
参数:id :必选项为字符串(String)
返回值:对象; 返回相同id对象中的第一个,按在页面中出现的次序,如果无符合条件的对象,则返回 null
example:
document.getElementById("id1").value;
4、getElementsByClassName
作用:返回文档中所有指定类名的元素集合,作为 NodeList 对象。NodeList 对象代表一个有顺序的节点列表。NodeList 对象 我们可通过节点列表中的节点索引 号来访问列表中的节点(索引号由0开始)。
提示: 你可以使用 NodeList 对象的 length 属性来确定指定类名的元素个数,并循环各个元素来获取你需要的那个元素。
5、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;
6、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的值