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>
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.