Kate Wintz
Kate Wintz

Reputation: 643

Check for the class in an element

If there is an element with the class myclass in the #main element, I want to alert ok but in my example it always shows no, how can fix this?

Demo: http://jsfiddle.net/mF2K6/1/

<form>
    <div id="main">
        <div class="myclass"></div>
    </div>
    <button>Click Me</button>
</form>


$('button').live('click', function (e) {
    e.preventDefault();
    //var copy_html = $('#main').clone();
    //if ($('#main').hasClass('myclass')) {
    if ($('#main').is('.myclass')) {
        alert('ok');
    } else {
        alert('no');
    }
})

Upvotes: 1

Views: 601

Answers (4)

island205
island205

Reputation: 1740

this will work fine:jsfiddle

var main=$("#main");
$("button").click(function(){
    if(!!main.find(".myclass").length){
        alert("ok");
    }else{
        alert("no");
    };
});

[0]is method can't to compare different doms!

[1]why must use live?

[2]cache main(jQuery Object) is more efficient.select only ones.

Upvotes: 0

jabclab
jabclab

Reputation: 15062

Something like this should help:

$("button").click(function () {
    window.alert(isClassPresent() ? "Yes" : "No");
});

function isClassPresent() {
    return $("#main .myclass").length > 0;
}

Upvotes: 0

jfriend00
jfriend00

Reputation: 708156

To check sub-elements for myclass, use this:

if ($('#main').find('.myclass').length != 0)

or this:

if ($('#main .myclass').length != 0)

Upvotes: 2

KARASZI Istv&#225;n
KARASZI Istv&#225;n

Reputation: 31477

Your <div id="main"> does not have myclass class, only one of its children has it.

You can check the latter with the following code:

if ($("#main .myclass").length > 0) {
  alert('ok');
} else {
  alert('no');
}

Upvotes: 1

Related Questions