Reputation: 83
i want to check if i have elements with a matched className that is being dynamically generated and apply some code in this case :
say:
<div class="c red"></div>
<div class="c green"></div>
<div class="c red"></div>
<div class="c yellow"></div>
<div class="c red"></div>
i want to check if for those tags that has class "red" and apply something to them but keep in mind that i cant call the $(".red") element directly because it can vary each time the page load and become diffrent color next time , so i want a generic solution to check if there is a match in class names in the document
Upvotes: 1
Views: 455
Reputation: 235962
Using jQuery:
$('div.c').each(function(_, div) {
if( $(div).hasClass( 'red' ) ) {
// this div node has a class called 'red'
}
});
You can either use .hasClass()
or .is()
to determine that. Be aware that when using .is()
you need to qualify the string with a leading dot, like '.red'
.
Using vanilla Javascript:
[].forEach.call( document.querySelectorAll( 'div.c' ), function( div ) {
if( div.classList.contains( 'red' ) ) {
// this div node has a class called 'red'
}
});
Upvotes: 2