rockyraw
rockyraw

Reputation: 1145

How to exclude an element from jquery function?

when a table is being hovered, I have a function that adds a certain class to some element.

In that table, I want this behavior for all elements except one.

therefore in the code, I included th,td,td span,td p,td div.good,

But - I have a specific span (<span class="foo">) inside the table which I want to exclude, how can I do it?

(I'm not a JS coder so after looking in previous q's, still not sure about the most recommended way to do this in my context)

Code:

<script>
$(document).ready(function(){
$(function(){
    $('th,td,td span,td p,td div.good').mouseenter(function(){
        $(".light").addClass('altbg')
    }).mouseout(function(){
        $(".light").removeClass('altbg')
    });
});
})
</script>

Upvotes: 0

Views: 142

Answers (2)

Alnitak
Alnitak

Reputation: 339786

Although it's possible to use .not() to exclude a set of elements from an existing selector, arguably your code is inefficient because it registers the two event handlers against a large set of elements and the callbacks will be invoked repeatedly as you move your mouse around the table.

Consider this, instead:

$('table,.foo').on('mouseenter mouseleave', function (e) {
    $('.light').toggleClass('altbg');
});

There are only two elements listening for the mouse events - the table itself, and the span you wish to ignore. Since you cannot reach the inner span without crossing the table this will produce the desired effect.

See http://jsfiddle.net/alnitak/eecqkx6v/

Upvotes: 3

Patrick Evans
Patrick Evans

Reputation: 42736

Use the jquery .not method to exclude elements

$('th,td,td span,td p,td div.good').not(".foo")

jQuery .not documentation

Also you do not have to use both the .ready method along with the passing a function to $() they will do the same thing.

$(function(){
    $('th,td,td span,td p,td div.good').not(".foo").mouseenter(function(){
        $(".light").addClass('altbg')
    }).mouseout(function(){
        $(".light").removeClass('altbg')
    });
});

is all you need

Upvotes: 2

Related Questions