user2381011
user2381011

Reputation: 351

Select li classname if it exists

Each time a button is clicked i'm entering a function where I check if a listitem with specific classname exists. If it exists, then it has to be removed.

if($("ul#" + this.listClass + " li[class='errorlist']"))
{
    console.log("error");
}

Now, it enters the function each time I click, even if it doesn't exist.

Thanks in advance.

Upvotes: 0

Views: 744

Answers (2)

Ron van der Heijden
Ron van der Heijden

Reputation: 15080

This could help

var test = document.getElementById('test') //returns a HTML DOM Object
var test = $('#test') //returns a jQuery Object
var test = $('#test')[0] //returns a HTML DOM Object

So you can use if($('#test')[0]) to check if the element exists in the DOM.

Example also to check if the element has a class

if($('#test')[0] && $('#test').hasClass("test")) {
    $('#test').removeClass("test");
}

Upvotes: 1

Henrik Andersson
Henrik Andersson

Reputation: 47222

If you want to check for class existing

if($('myElement').hasClass('myClassToCheckFor')){
    //do stuff to my element here
}

if you want to check for element existing

if($('myElement.withMyClass').length > 0) {
    //do stuff to my element here
}

So what you want to do is this (this is however not optimized for caching of jquery object but it demonstrates what you need to do).

$('button.myButton').click(function(){
    if($('ul li').hasClass('monkey')){
        $('ul li.monkey').remove();
    } else {
        alert("not found!");
    }
});

See this fiddle

Upvotes: 1

Related Questions