首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

DOM扩张-选择符API

2014-02-19 
DOM扩展-----选择符API//核心:通过CSS 选择符查询DOM文档取得元素的引用//querySelector()方法,返回匹配的

DOM扩展-----选择符API
//核心:通过CSS 选择符查询DOM文档取得元素的引用//querySelector()方法,返回匹配的第一个元素,没有匹配的返回null//取得body 元素var body = document.querySelector("body");//取得ID 为"myDiv"的元素var myDiv = document.querySelector("#myDiv");//取得类为"selected"的第一个元素var selected = document.querySelector(".selected");//取得类为"button"的第一个图像元素var img = document.body.querySelector("img.button");//querySelectorAll()方法,返回的是所有匹配的元素//取得某<div>中的所有<em>元素(类似于getElementsByTagName("em"))var ems = document.getElementById("myDiv").querySelectorAll("em");//取得类为"selected"的所有元素var selecteds = document.querySelectorAll(".selected");//取得所有<p>元素中的所有<strong>元素var strongs = document.querySelectorAll("p strong");//matchesSelector()方法,这个方法接收一个参数,即CSS 选择符,//如果调用元素与该选择符匹配,返回true;否则,返回false。function matchesSelector(element, selector){if (element.matchesSelector){return element.matchesSelector(selector);} else if (element.msMatchesSelector){return element.msMatchesSelector(selector);} else if (element.mozMatchesSelector){return element.mozMatchesSelector(selector);} else if (element.webkitMatchesSelector){return element.webkitMatchesSelector(selector);} else {throw new Error("Not supported.");}}if (matchesSelector(document.body, "body.page1")){//执行操作}

?

热点排行