自定义方法通过类名获取对象集合
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p class="test test1">class -> test test1</p>
<p class="test test1 test2">class -> test test1 test2</p>
<p class="test test2">class -> test test2</p>
<script>
function classSelectors(className, tagName) {
// return [...document.getElementsByTagName(tagName || '*')].filter(function (value) {
// return className.split(' ').every(function (elem) {
// return value.className.split(' ').includes(elem)
// })
// });
return [...document.getElementsByTagName(tagName || '*')].filter(value => className.split(' ').every(elem => value.className.split(' ').includes(elem)));
}
// 获取首个添加背景和字体颜色测试
classSelectors('test test2', 'p').shift().style.cssText = 'background:yellow;color:red';
console.log(classSelectors('test test2', 'p'));
</script>
</body>
</html>