通过id获取Dom
function $(id) {
if (type id !== 'string') { throw new Error('参数id必须是字符串');}
const dom = document.getElementById(id);
if (!dom) { throw new Error('dom对象未找到'); }
return dom;
}
通过class获取dom
function getClassName(className) {
if (type className !== 'string') { throw new Error('参数className必须是字符串');}
const dom = document.getElementByClassName(className);
if (!dom) { throw new Error('dom对象未找到');}
return dom;
}
注:获取的是数组集合
通过标签获取dom
function getTagName(tagName) {
if (type tagName !== 'string') { throw new Error('参数tagName必须是字符串');}
const dom = document.getElementByTagName(tagName);
if (!dom) { throw new Error('dom对象未找到');}
return dom;
}
注:获取的是数组集合
通过name属性获取dom
<input type="text" name="user" />
function getName(name) {
if (type name!== 'string') { throw new Error('参数name必须是字符串');}
const dom = document.getElementByName(name);
if (!dom) { throw new Error('dom对象未找到');}
return dom;
}
注:获取的是数组集合
通过选择器querySelector()
和querySelectorAll()
获取dom
<div class="box">box1</div>
<div class="box">box2</div>
<div class="box">box3</div>
<div class="box">box4</div>
<div class="box">box5</div>
<script>
let box1= document.querySelector(".box");
let boxes= document.querySelectorAll(".box");
</script>
注:querySelector()获取的是单个对象,querySelectorAll()获取的是数组对象;
网友评论