0

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.

4

2 回答 2

1

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

于 2013-05-17T07:51:23.920 回答
1

这可能会有所帮助

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

所以你可以if($('#test')[0])用来检查元素是否存在于 DOM 中。

示例还检查元素是否具有类

if($('#test')[0] && $('#test').hasClass("test")) {
    $('#test').removeClass("test");
}
于 2013-05-17T07:56:09.730 回答