Reputation: 351
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
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
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!");
}
});
Upvotes: 1