Contention
Contention

Reputation: 691

Adding class to jQuery object that has been passed to a function

I have a simple jQuery function that adds a class (.dataerror) to various html elements if they are empty. First, I'm doing this:

$('.editable').each(function() {
    if (!$(this).html()) {
        showerror($(this));
    }
});

And a super-simplified version of the function looks like this:

function showerror(element) {
    $(element).addClass('dataerror');
}

However, this DOES NOT add the class to the elements if they are empty.

If I change the function to:

function showerror(element){
    $(element).hide();
}

...then the elements ARE hidden as expected if they are empty.

Can anyone tell my why .addClass() DO NOT work on the element in this context, while other methods such as .hide() DO work?

Thx.

Upvotes: 0

Views: 31

Answers (2)

Lim H.
Lim H.

Reputation: 10050

Use showerror(this); instead of showerror($(this)) because you are wrapping the DOM element into a jquery object twice.

Upvotes: 1

abhiklpm
abhiklpm

Reputation: 1653

Instead of

$(element).addClass('dataerror');

can u try

element.addClass('dataerror');

Upvotes: 1

Related Questions