面試題-實現一個 $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);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章