getElementById()
getElementById()方法接收一个参数:要取得元素的ID,若找到相应元素则返回该元素,若不存在则返回null
【IE7-浏览器bug1】ID属性不区分大小写
<div id="box"></div><script>var oBox = document.getElementById('Box');console.log(oBox);//IE7-可以找到该元素,但其他浏览器都返回null</script>
如果页面中多个元素的ID属性相同,则只返回文档中第一次出现的元素
<div id="box">1</div><div id="box">2</div><script>var oBox = document.getElementById('box');console.log(oBox.innerHTML);//1</script>
【IE7-浏览器bug2】表单元素的name属性也会被当作ID属性识别出来。因此为了避免这种问题,最好不让表单元素的name属性和其他元素的ID属性相同
<button name="box">0</button><div id="box">1</div><div id="box">2</div><script>var oBox = document.getElementById('box');console.log(oBox.innerHTML);//0</script>
getElementsByTagName()
getElementsByTagName()该方法接收一个参数,即要取得元素的标签名,而返回的是包含0或多个元素的NodeList。在HTML文档中,这个方**返回一个HTMLCollection对象,作为一个动态集合,该对象与NodeList非常类似。对于HTMLCollection对象而言,我们可以向方括号中传入数值或字符串形式的索引值。在后台,会对数值索引调用item()方法,对字符串索引调用namedItem()方法。HTMLCollection对象还有一个方法是namedItem(),可以通过元素的name特性或者直接用方括号来取得集合中的项。但safari和IE都不支持该方法。
<ul id="list"> <li >1</li> <li >2</li> <li name="in3">3</li> </ul><script>var oList = document.getElementById('list');var aIn = oList.getElementsByTagName('li');console.log(aIn.length);//3console.log(aIn[0].innerHTML);//1console.log(aIn.item(0).innerHTML);//1console.log(aIn["in3"].innerHTML);//在safari和IE下报错,在其他浏览器下输出3console.log(aIn.namedItem("in3").innerHTML);//在safari和IE下报错,在其他浏览器下输出3
要想取得所有的元素,可以向getElementsByTagName传入"*",表示全部
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title></head><body><script>var aAll = document.getElementsByTagName('*');//标准浏览器下结果为[html, head, meta, title, body, script]//IE8-浏览器下结果为7个,由于它把<!DOCTYPE html>识别为注释,且把注释识别为元素,所以多1个console.log(aAll);</script></body></html>
在HTML中getElementsByTagName()里的元素不需要区分大小写,但在
<div id="box">1</div><script>var aAll = document.getElementsByTagName('DIV')[0];console.log(aAll.innerHTML);//所有浏览器都返回1</script>
getElementsByName()
getElementsByName()该方**返回带有给定name特性的所有元素,所有浏览器都支持。
最常用的是取得单选按钮。
<ul > <li > <input type="radio" value ="red" name ="color" id="colorRed"> <label for="colorRed">红色</label> </li> <li > <input type="radio" value ="blue" name ="color" id="colorBlue"> <label for="colorBlue">蓝色</label> </li> <li > <input type="radio" value ="green" name ="color" id="colorGreen"> <label for="colorGreen">绿色</label> </li> </ul><script>var radios = document.getElementsByName('color');console.log(radios.length)//3</script>
getElementsByClassName()
getElementsByClassName()方法接收一个参数,即一个包含一个或多个类名的字符串,返回带有指定类的所有元素的NodeList。传入多个类名时,类名的先后顺序不重要。(IE8-浏览器不支持)
<ul > <li >1</li> <li >2</li> <li >3</li></ul> <script>var oTest = document.getElementsByClassName('in ab');console.log(oTest.length);//2</script>
classList
在操作类名时,需要通过className属性添加、删除和替换类名。因为className是一个字符串,所以即使只修改字符串一部分,也必须每次都设置整个字符串的值。要从className字符串中删除一个类名,需要把类名拆开,删除不想要的那个,再重新拼成一个新字符串。(IE9-浏览器不支持)
<ul > <li >1</li> <li >2</li> <li >3</li></ul> <script>var oTest = document.getElementsByClassName('in ab')[1];function removeClass(obj,str){ var classNames = obj.className.split(/\s+/); var pos = -1; for(var i = 0, len = classNames.length; i < len; i++){ if(classNames[i] == str){ pos = i; break; } }; classNames.splice(i,1); obj.className = classNames.join(' ');}removeClass(oTest,'in');console.log(oTest.className)//ab c</script>
HTML5为所有元素添加了classList属性,这个classList属性是新集合类型DOMTokenList的实例,它有一个表示自己包含多少元素的length属性,而要取得每个元素可以使用item()方法,也可以使用方括号法。此外,这个新类型还定义如下方法:
add(value):将给定的字符串值添加到列表中,如果值已存在,则不添加
contains(value):表示列表中是否存在给定的值,如果存在则返回true,否则返回false
remove(value):从列表中删除给定的字符串
toggle(value):如果列表中已经存在给定的值,删除它;如果列表中没有给定的值,添加它。
<ul > <li >1</li> <li >2</li> <li >3</li></ul> <script>var oTest = document.getElementsByTagName('li')[1];console.log(oTest.classList);//IE9-浏览器返回null,其他浏览器返回["in", "ab"]//删除"in"类oTest.classList.remove("in");console.log(oTest.className);//ab//添加"x"类oTest.classList.add("x");console.log(oTest.className);//ab x//切换"in"类oTest.classList.toggle("in");//ab x inconsole.log(oTest.className);//切换"in"类oTest.classList.toggle("in");//ab xconsole.log(oTest.className);//确定是否包含"in"类console.log(oTest.classList.contains("in"));//false</script>
querySelector()
querySelector()方法接收一个CSS选择符,返回与该模式匹配的第一个元素,如果没有找到匹配的元素,返回null(IE7-浏览器不支持)
<body ><div id="box" ><ul > <li >1</li> <li title="test">2</li> <li >3</li> </ul> </div><script>//返回nullvar oNull = document.querySelector('.null');console.log(oNull);//null//取得body元素var body = document.querySelector("body");console.log(body.style.height);//100%//取得ID为"box"的元素var oBox = document.querySelector('#box');console.log(oBox.style.height);//200px//取得第一个class为"list"的ul元素var oList = document.querySelector('ul.list');console.log(oList.style.height);//100px//取得第一个class为"in"的元素var oIn = document.querySelector('.in');console.log(oIn.innerHTML);//1//取得第一个title属性为test的元素var oTest = body.querySelector('[title="test"]');console.log(oTest.innerHTML);//2</script></body>
querySelectorAll()
querySelectorAll()接收一个CSS选择符,返回一个NodeList的实例。具体来说,返回的值实际上是带有所有属性和方法的NodeList,而其底层实现则类似于一组元素的快照,而非不断对文档进行搜索的动态查询。这样实现可以避免使用NodeList对象通常会引起的大多数性能问题。只要传给querySelectorAll()方法的CSS选择符有效,该方法都会返回一个NodeList对象,而不管找到多少匹配的元素。如果没有找到匹配的元素,NodeList就是空的。(IE7-浏览器不支持)
<body ><div id="box" ><ul > <li >1</li> <li title="test">2</li> <li >3</li> </ul> </div><script>//返回nullvar oNull = document.querySelectorAll('.null');console.log(oNull);//null//取得body元素var body = document.querySelectorAll("body")[0];console.log(body.style.height);//100%//取得所有class为"in"的元素var oIn = document.querySelectorAll('.in');for(var i = 0 ; i < oIn.length; i++){ console.log(oIn[i].innerHTML);//1,2,3 }//取得title属性为test的元素var oTest = body.querySelectorAll('[title="test"]');console.log(oTest);//[li.in]</script></body>
matchesSelector()
matchesSelector()方法接收一个CSS选择符参数,如果调用元素与该选择符相匹配,返回true;否则返回false(暂无浏览器支持)
console.log(document.body.matchesSelector('body'));//true
但IE9+浏览器支持msMatchesSelector()方法,firefox支持mozMatchesSelector()方法,safari和chrome支持webkitMatchesSelector()方法。所以兼容写法为:
function matchesSelector(element,selector){ if(element.matchesSelector){ return element.matchesSelector(selector); } if(element.msMatchesSelector){ return element.msMatchesSelector(selector); } if(element.mozMatchesSelector){ return element.mozMatchesSelector(selector); } if(element.webkitMatchesSelector){ return element.webkitMatchesSelector(selector); } }console.log(matchesSelector(document.documentElement,'html'));//true
原标题:DOM选择器API
关键词:dom