2017-06-04 16 views
1

"category-lifestyle"または"category-magazine"のような特定の接頭辞に基づいてクラスを抽出したいとします。特定の接頭辞で始まるすべてのクラス名をJavaScript/jQueryで取得する

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> 
+1

の可能性のある重複した[?jqueryのすべてのクラス要素を選択する方法は、 "テキストベース" で始まる](https://stackoverflow.com/questions/4161869/jquery-how-to-select-all-the-class-elements-start-with-text) – Liam

+0

@Javid誰かがあなたの問題を解決しましたか?もしそうなら、あなたは最高の答えを受け入れてください(ポイントの下にあるチェックマークをクリックしてください)。それはあなたの質問に出くわす他のユーザーがすぐに受け入れられた答えを見つけるのを助け、15人の担当者も与えます。 ( – Danziger

答えて

0

次のセレクタを使用することができます:あなたがで始まるすべてのクラスのリストを取得したい場合は、のは言わせ

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

いいえ、私はクラス名を取得する必要があります – Javid

+1

次にクラスリストを検索します... [常に回答している](https://stackoverflow.com/questions/1227286/get-class- j-for-with-jquery) –

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>

関連する問題