使用JavaScript / jQuery获取以特定前缀开头的所有类名

时间:2017-06-04 09:38:41

标签: javascript jquery

我想根据"category-lifestyle""category-magazine"等特定前缀提取类。

HTML标记如下所示:

<article id="post-361" class="et_pb_post post-361 post type-post status-publish format-standard has-post-thumbnail hentry category-lifestyle category-magazine">

    Post content... 

</article>

2 个答案:

答案 0 :(得分:0)

您可以使用以下选择器:

console.log(
   document.querySelectorAll("article[class*='category-lifestyle']")[0].innerHTML
);

答案 1 :(得分:0)

如果你想得到一个开头的所有类的列表,比如说category-,你应该首先使用attribute contains selector得到包含匹配类的所有元素:

document.querySelectorAll("*[class*='category-']")

然后你应该提取这些元素的所有类,并过滤掉重复项和那些不以所需前缀开头的副本。

这样的事情:

const allCategoryClasses = [];

// Get all elements that have any class starting
// with 'category-':

const elementsWithCategoryClasses
  = document.querySelectorAll("*[class*='category-']");

const elementsCount = elementsWithCategoryClasses.length;

for (let i = 0; i < elementsCount; ++i) {
  // Append all the classes of the matching elements to
  // allCategoryClasses.

  // Note we are not filtering out the other classes that
  // do not start with 'category-' yet.
  
  Array.prototype.push.apply(
    allCategoryClasses,
    elementsWithCategoryClasses[i].classList
  );
}

// Now filter out the classes that do not start with
// 'category-' here, so we do it just one time, instead
// of doing it once for each single element.

// Also, use and object to remove duplicates.

const presentClasses = {};

console.log(allCategoryClasses
  .filter((classname) => {
    const present = presentClasses[classname];
    
    presentClasses[classname] = true;
    
    return classname.indexOf("category-") === 0 && !present;
  }));
    
// This will also filter out duplicates:

// const presentClasses = {};

// allCategoryClasses
//   .forEach((classname) => {
//     if (classname.indexOf("category-") === 0) {
//       presentClasses[classname] = true;
//     }
//   });
  
// console.log(Object.keys(presentClasses));
<div class="category-a other-class"></div>
<div class="other-class category-b"></div>
<div class="category-c category-d other-class"></div>
<div class="category-e other-class category-f"></div>
<div class="other-class"></div>
<div class="category-e other-class category-f"></div>