檢查元素是否包含 JavaScript 中的類? - Check if an element contains a class in JavaScript?

問題:

Using plain JavaScript (not jQuery), Is there any way to check if an element contains a class?使用普通的 JavaScript(不是 jQuery),有沒有辦法檢查一個元素是否包含一個類?

Currently, I'm doing this:目前,我正在這樣做:

var test = document.getElementById("test"); var testClass = test.className; switch (testClass) { case "class1": test.innerHTML = "I have class1"; break; case "class2": test.innerHTML = "I have class2"; break; case "class3": test.innerHTML = "I have class3"; break; case "class4": test.innerHTML = "I have class4"; break; default: test.innerHTML = ""; }
<div id="test" class="class1"></div>

The issue is that if I change the HTML to this...問題是,如果我將 HTML 更改爲此...

<div id="test" class="class1 class5"></div>

...there's no longer an exact match, so I get the default output of nothing ( "" ). ...不再有完全匹配,所以我得到的默認輸出沒有( "" )。 But I still want the output to be I have class1 because the <div> still contains the .class1 class.但我仍然希望輸出是I have class1因爲<div>仍然包含.class1類。


解決方案:

參考一: https://stackoom.com/question/OkVc
參考二: Check if an element contains a class in JavaScript?
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章