检查匹配的类名并执行某些操作

时间:2012-07-30 23:43:42

标签: javascript jquery

我想检查一下我是否拥有一个动态生成的匹配className的元素,并在这种情况下应用一些代码:

说:

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

我想检查那些具有“红色”类的标签是否适用于它们 但请记住,我不能直接调用$(“。red”)元素,因为它可以在每次页面加载时变化,并在下次变为不同颜色,所以我想要一个通用的解决方案来检查类名中是否匹配在文件中

1 个答案:

答案 0 :(得分:2)

使用jQuery:

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

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

使用vanilla Javascript:

[].forEach.call( document.querySelectorAll( 'div.c' ), function( div ) {
    if( div.classList.contains( 'red' ) ) {
        // this div node has a class called 'red'
    }
});