简体   繁体   English

如何将包含连字符/破折号(?)的所有类应用于任何 DOM 元素并将它们保存到 JavaScript 的数组中?

[英]How to get all classes containing hyphen/dash(?) applied to any DOM element and save them into array in JavaScript?

How to get all classes containing hyphen/dash(?) applied to any DOM element and save them into array in JavaScript?如何将包含连字符/破折号(?)的所有类应用于任何 DOM 元素并将它们保存到 JavaScript 的数组中?

My failing approach:我失败的方法:

 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); } });

Your attempt is fairly close to working.您的尝试非常接近工作。 The problem is you're pushing an array into getClasses rather than the individual classes, and neither strings nor arrays have a standard contains method (there's includes , which is probably what you mean).问题是您将数组推入getClasses而不是单个类,并且字符串和 arrays 都没有标准contains方法(有includes ,这可能是您的意思)。 Also, if you only want ones containing - , you can filter them out earlier:此外,如果您只想要包含-的内容,您可以提前过滤掉它们:

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];

Live Example:现场示例:

 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>


(I have never understood why Set doesn't have an addAll method, or at least accept multiple values to add like push does...) (我从来不明白为什么Set没有addAll方法,或者至少像push一样接受多个值来add ......)

The thing you are not realizing is that you are pushing an array of classes into your getClasses array.您没有意识到的是您正在将一个类数组推入您的getClasses数组。 So you end up with an array of arrays, aka a 2-dimensional array.所以你最终得到了一个 arrays 数组,也就是一个二维数组。

Note, too, that you can do your extracting of classes and filtering to only those that contain dashes in one step, rather than having to process the list twice.还要注意,您可以在一个步骤中提取类并仅过滤那些包含破折号的类,而不必处理列表两次。

 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>

Use document.querySelectorAll() with an attribute selector to get all elements with a class that includes ( =* ) an hyphen.document.querySelectorAll()属性选择器一起使用,以获取包含 ( =* ) 连字符的 class 的所有元素。 Convert the results to an array using Array.from() .使用Array.from()将结果转换为数组。 Now iterate the elements with Array.flatMap() , get the classlist and convert to an array, and filter out classes that don't include a hyphen.现在使用Array.flatMap()迭代元素,获取classlist并转换为数组,并过滤掉不包含连字符的类。 Use a Set to make the items unique, and spread back to an array.使用 Set 使项目唯一,并传播回数组。

 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 ab something-else xy"></div> <div class="something"></div> <div class="ab cd"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM