Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery check if attribute contain substring

Tags:

jquery

Here's my problem: Consider the following html:

<div id="item1" class="green_large">
<div id="item2" class="green_large">
<div id="item2" class="green_small">
<div id="item4" class="yellow_large">
<div id="item5" class="yellow_large">

How do I check if $(this) contain a class name with the substring "yellow" for example using jQuery?

$("div").click(function() {

    if ($(this).contains_the_class_with_the_substring_yellow?) {
        // do something
    }
}
like image 804
Tom Avatar asked Oct 12 '10 12:10

Tom


2 Answers

$("div").click(function() {

    if (this.className.indexOf("yellow") > -1) {
        // do something
    }
}
like image 62
Mikee Avatar answered Dec 13 '22 22:12

Mikee


$("div").click(function() {

    if (this.className.indexOf('yellow') > -1) {
        // do something
    }
}

or pure jQuery'ish:

$("div").click(function() {

    if ($(this).attr('class').indexOf('yellow') > -1) {
        // do something
    }
}
like image 20
jAndy Avatar answered Dec 13 '22 22:12

jAndy