1

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

4

1 回答 1

2

使用 jQuery:

$('div.c').each(function(_, div) {
    if( $(div).hasClass( 'red' ) ) {
        // this div node has a class called 'red'
    }
});

您可以使用.hasClass().is()确定。请注意,在使用时,.is()您需要使用前导点来限定字符串,例如'.red'.

使用香草 Javascript:

[].forEach.call( document.querySelectorAll( 'div.c' ), function( div ) {
    if( div.classList.contains( 'red' ) ) {
        // this div node has a class called 'red'
    }
});
于 2012-07-30T23:44:58.880 回答