面试题-实现一个 $attr(name, value)遍历,属性为 name,值为 value 的元素集合

实现一个 $attr(name, value)遍历,属性为 name,值为 value 的元素集合

let arr = $attr(‘class’, ‘box’); => 获取页面中所有 class 为 box 的元素

来看看我们该如何解决:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>$attr</title>
</head>
<body>
	<div id="AA" class="box"></div>
	<div test="1"></div>
	<div class="content box"></div>
	<div name="bb"></div>
	<div></div>
	<div id="BB"></div>
	<div test="1"></div>
	<div class="box"></div>
	<div test="2"></div>
	<div name="BB"></div>
	<div class="clearfix"></div>
</body>
</html>
<script type="text/javascript" src="./index.js"></script>

index.js

function $attr(prototype, value) {
    
    
	// 获取页面中所有的标签
	let elements = document.getElementsByTagName('*'),
		arr = [];
	// 将类数组循环--使用数组的 forEach
	[].forEach.call(elements, function(item){
    
    
		// 获取到要找的属性值
		let itemVal = item.getAttribute(prototype);
		// 样式类做特殊处理
		if (prototype === 'class') {
    
    
			// 将这个 value 值作为正则,以这个 value 值开头并结尾才可以
			// 比如 box
			// reg.test("con box")  => true
			// reg.test("conbox")   => false
			// 这里不适用直接用 indexOf 和 inculdes,用这两个还得做处理,
			// 用正则最简单
			new RegExp("\\b"+ value +"\\b").test(itemVal) ? 
			arr.push(item) : null;
			return;
		}
		// 判断获取到的属性值是否和我们需要的值相等
		if (itemVal === value) {
    
    
			arr.push(item);
		}
	})

	// 或者使用 array 的 from 方法,把一个非数组转换为数组
	// elements = Array.from(elements);

	return arr;
}

let ary = $attr('class', 'box');
console.log(arr);

公众号:Coder 杂谈,欢迎关注
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_42345237/article/details/105176169