1

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.

Ralph David Abernathy
  • 5,230
  • 11
  • 51
  • 78

2 Answers2

2

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>
guest271314
  • 1
  • 15
  • 104
  • 177
1

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/

Aman Chhabra
  • 3,824
  • 1
  • 23
  • 39
  • How does the code at Answer check for specific text within value of `class` of element? – guest271314 Nov 02 '17 at 18:26
  • I have already printed the class name, if for any specific class any specific task needs to be executed, then an if check can be added in the for loop itself – Aman Chhabra Nov 02 '17 at 18:27