• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

250
Views
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>

about 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error