EnigmaRM
EnigmaRM

Reputation: 7632

Select all elements with same class

I'm looking to highlight all elements on a page that have the same class, on hover.

Code I have so far:

$(document).ready(function () {
$('p.myclass').mouseover(function () {
    $(this).addClass('hover');
});
$('p.myclass').mouseout(function () {
    $(this).removeClass('hover');
});
});

My brief example: JSFiddle

Currently it highlights only the element that I'm hovered over. But I would like it to highlight ALL elements that have the same class. How would this be done? I am not particular whether it is done in CSS3 or Jquery.

Upvotes: 1

Views: 145

Answers (2)

user1726343
user1726343

Reputation:

Since mouseover attaches an event handler to each element in your queried collection individually, the value of this inside the callback is the element that you are hovering over, and not the entire collection. Instead of this, use the selector.

$('p.myclass').mouseover(function () {
    $('p.myclass').addClass('hover');
});

Alternatively, you could cache your collection and refer to it for modest savings in terms of efficiency:

var coll = $('p.myclass');
coll.mouseover(function () {
    coll.addClass('hover');
});

Upvotes: 3

Tamil Selvan C
Tamil Selvan C

Reputation: 20199

Use

$(document).ready(function () {
$('p.myclass').mouseover(function () {
    $('p.myclass').addClass('hover');
});
$('p.myclass').mouseout(function () {
    $('p.myclass').removeClass('hover');
});
});

Upvotes: 1

Related Questions