<body>
<div class="box clearfix"></div>
<div name="zs"></div>
<div class="box"></div>
<div name="ls"></div>
<div class="attr"></div>
<div class="box2"></div>
<div class="box A"></div>
</body>
--------------------------------------------------------------------------------------------------------------------------------------
function $attr(property, value) {
// 获取当前页面中所有的标签
let elements = document.getElementsByTagName('*'),
arr = [];
elements = Array.from(elements); // => 把非数组转换为数组
elements.forEach(item => {
// => 储存的是当前元素 property 对应的属性值
let itemValue = item.getAttribute(property);
if (property === 'class') {
// => 样式类属性名要特殊处理
new RegExp("\b" + value + "\b").test(itemValue) ? arr.push(item) : null;
return;
}
if (itemValue === value) {
// => 获取的值和传递的值校验成功
arr.push(item);
}
});
return arr;
}
console.log($attr('class', 'box'));