Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use javascript to check if class that starts with (classname__) exists?

In the snippet below, I’m using the contains() method to check if a class that starts with banner__ exists in the document. If I define the class explicitly, then I can get a true response. But there are various classes that could exist in the document that start with banner__.

How do I check if a class that starts with banner__ exists?

const banner = document.querySelector('.banner');
const isBanner = banner.classList.contains('banner__');
if (isBanner) {
  console.log('Exists')
} else {
  console.log('Does not exist')
}
<div class="banner banner__holiday">Banner</div>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Convert the class list to an array, then use .some() to test if any of them begin with what you want.

const banner = document.querySelector('.banner');
const isBanner = Array.from(banner.classList).some(c => c.startsWith('banner__'));
if (isBanner) {
  console.log('Exists')
} else {
  console.log('Does not exist')
}
<div class="banner banner__holiday">Banner</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading