Ralph David Abernathy
Ralph David Abernathy

Reputation: 5518

How to check if all class names of divs in the DOM have a specific string with vanilla Javascript?

I have the following markup:

<div id="app">
  <div class="1hidden1></div>
  <div class="123"></div>
  <div class="hidden"></div>
</div>

How can I check if a div in the DOM has a class name that contains the text hidden? The desired output would be true for the above code.

Here is what I have so far, but this only checks for the third div in the example above:

if (document.getElementById('app').classList.contains('hidden')) {
  // this does not select the first div within #app
}

I would like to check for both the third and first div -- any div that contains a class name with the text hidden.

Upvotes: 1

Views: 269

Answers (2)

guest271314
guest271314

Reputation: 1

You can use .querySelectorAll() and attribute contains selector, check the .length of the returned NodeList and use !! operator to get a Boolean value

var hidden = document.querySelectorAll("#app [class*='hidden']");

console.log(!!hidden.length, hidden);
<div id="app">
  <div class="1hidden1"></div>
  <div class="123"></div>
  <div class="hidden"></div>
</div>

Upvotes: 2

Aman Chhabra
Aman Chhabra

Reputation: 3894

By using normal javascript you can use getElementsByTagName and then for each div found, you can check corresponding className

You can check the JSFiddle here:

var divs = document.getElementsByTagName("div");
for (i = 0, len = divs.length, text = ""; i < len; i++) { 
    console.log(divs[i].className);
}

https://jsfiddle.net/dttw8fcb/

Upvotes: 1

Related Questions