如何将所有包含连字符/破折号(?(的类应用于任何DOM元素,并将它们保存到JavaScript中的数组中?
我失败的方法:
var getClasses = [];
var classesContain = [];
document.querySelectorAll('*').forEach( x => {
var y = x.className.split(' ');
getClasses.push(y);
});
getClasses.forEach( c => {
if(c.contains('-')){
classesContain.push(c);
}
});
您的尝试已接近成功。问题是,您将数组推入getClasses
,而不是单个类,并且字符串和数组都没有标准的contains
方法(有includes
,这可能就是您的意思(。此外,如果你只想要包含-
的,你可以早点过滤掉:
let classesWithDash = new Set();
document.querySelectorAll('*').forEach(element => {
for (const cls of element.className.split(' ').filter(name => name.includes("-"))) {
classesWithDash.add(cls);
}
});
// Now, `classesWithDash` is a set containing the class names with dashes
// If you want an array:
classesWithDash = [...classesWithDash];
实例:
let classesWithDash = new Set();
document.querySelectorAll('*').forEach(element => {
for (const cls of element.className.split(' ').filter(name => name.includes("-"))) {
classesWithDash.add(cls);
}
});
// Now, `classesWithDash` is a set containing the class names with dashes
// If you want an array:
classesWithDash = [...classesWithDash];
console.log(classesWithDash);
<div class="foo foo-bar"></div>
<div class="another-one"></div>
<div class="nodash"></div>
(我一直不明白为什么Set
没有addAll
方法,或者至少像push
那样接受add
的多个值…(
将document.querySelectorAll()
与属性选择器一起使用,可以获取包含(=*
(连字符的类的所有元素。使用Array.from()
将结果转换为数组。现在用Array.flatMap()
迭代元素,得到classlist
并转换为数组,过滤掉不包含连字符的类。使用"集合"使项目具有唯一性,并展开为数组。
const result = [...new Set( // use a Set to get an array of unique items
Array.from(document.querySelectorAll('[class*="-"]')) // select all elements with classes that contain hyphens
.flatMap(el => Array.from(el.classList).filter(c => c.includes('-'))) // create an array of all classes with hyphens
)]
console.log(result)
<div class="something a-b something-else x-y"></div>
<div class="something"></div>
<div class="a-b c-d"></div>
您没有意识到的是,您正在将一个类数组推送到getClasses
数组中。最后得到一个数组,也就是二维数组。
还要注意的是,您可以在一个步骤中提取类并只过滤那些包含短划线的类,而不必处理两次列表。
var classesContain = [];
document.querySelectorAll('*').forEach(x => {
var y = (x.className || '').split(/s+/g); // use a regex to cater for multiple spaces
y.forEach(className => {
if (className.includes('-'))
classesContain.push(className);
});
});
console.log('Final class list: ', classesContain);
<div class="foo-bar bar-baz foo">
<div class="foo-baz">
<span class="single">Example markup</span>
</div>
</div>