document.getElementById的简便方式

时间:2023-03-09 18:44:22
document.getElementById的简便方式

封装自己的元素获取方法,使元素获取变得简便

注意:1、应该要防止定义的被重写,可将同名的重新定义

     2、可将封装的对象置为全局对象,方便使用

通过id查找单个元素


封装方式:

//通过id查找单个元素
(function (document){
//防止覆盖
var _overwrite = window._,
_; _ = {
$ : function(id){
return typeof id === "string" ? document.getElementById(id) : id;
}
} //将_置为全局对象
window._ = _; })(document);

测试:

<!DOCTYPE html>
<html>
<body>
<div id = "cloud">The cloud is beautiful</div>
</body>
<script><!--
(function (document){
//防止覆盖
var _overwrite = window._,
_; _ = {
$ : function(id){
return typeof id === "string" ? document.getElementById(id) : id;
}
} //将_置为全局对象
window._ = _; })(document); var cloud = _.$("cloud");
alert(cloud.innerHTML); //The cloud is beautiful
--></script>
</html>

通过ID获取多个元素


封装方式:

//通过id查找一个或者多个元素
(function (document){
//防止覆盖
var _overwrite = window._,
_;
_ = {
$ : function(/*ids....*/){
var elements = {},
id,
elt;
for(var i = 0, len= arguments.length; i < len; i++){
id = arguments[i];
elt = document.getElementById(id);
if(elt === null){
throw new Error("No element with id:" + id);
}
if(len === 1){
return elt;
}
elements[id] = elt;
}
return elements;
}
} //将_置为全局对象
window._ = _; })(document);

测试:

 <div id = "cloud">The cloud is beautiful</div>
<div id = "sea">The white white sea</div>
//获取单个元素
var cloud = _.$("cloud");
alert(cloud.innerHTML);//The cloud is beautiful //获取多个元素
var all = _.$("cloud", "sea");
alert(all.cloud.innerHTML + "," + all.sea.innerHTML); //The cloud is beautiful,The white white sea