Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Select all elements with same class

Select all elements with same class

Problem

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.

Problem courtesy of: EnigmaRM

Solution

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');
});
Solution courtesy of: Asad Saeeduddin

Discussion

View additional discussion.



This post first appeared on CSS3 Recipes - The Solution To All Your Style Problems, please read the originial post: here

Share the post

Select all elements with same class

×

Subscribe to Css3 Recipes - The Solution To All Your Style Problems

Get updates delivered right to your inbox!

Thank you for your subscription

×