0

I have multiple elements with class test. If I hover them, they should have a red border around them because I wrap them around with div. It works, but how is it possible to wrap only active element, the one I'm hovering, not all the elements what have .test class?

$(".test").hover(function() {
 $(".sample").wrap('<div style="border: 1px solid red;" />');
}
Badr Hari
  • 8,114
  • 18
  • 67
  • 100
  • 1
    Have you tried `this`, in conjunction with some logic to select the desired element? `this` inside the function points to the currently selected element. You might want to use `$(this)` in order to perform jQuery methods. – Rob W Nov 30 '11 at 18:59
  • 1
    You will get better suggestions for how to do this if you include the relevant HTML. We don't know where the border goes relative to the thing you're hovering over (parent, child, sibling, same object, etc...) and that is relevant to selecting the best code for doing it. – jfriend00 Nov 30 '11 at 19:07

4 Answers4

0

You should use $(this) in the function. $(this) will refer to the currently hovered element.

$(".test").hover(function() {
    $(this).wrap('<div style="border: 1px solid red;" />');
});
jValdron
  • 3,408
  • 1
  • 28
  • 44
0

use $(this)

$(".test").hover(function() {
 $(this).wrap('<div style="border: 1px solid red;" />');
}
Evan
  • 5,975
  • 8
  • 34
  • 63
0

It would be a little more obvious how to help if you included your HTML. I will assume that the object with class="sample" is a parent object.

$(".test").hover(function() {
 $(this).closest(".sample").wrap('<div style="border: 1px solid red;" />');
});

You will, of course need to unwrap this when you stop hovering or put in code not to wrap it over and over again.

It would be better if you used an existing object for the border and just change the class or style on hover, unhover. Since I don't know what your HTML is, I can only guess what might be used:

$(".test").hover(function() {
   $(this).addClass("active");
}, function() {
   $(this).removeClass("active");
});

And, then have a CSS rule:

.active {border: 1px solid red;}
jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

I'm not sure if this is what you are looking for but this will wrap all your enabled elements with the class test.

$(".test:enabled").hover(function() {
    $(this).wrap('<div style="border: 1px solid red;" />');
});
xbrady
  • 1,683
  • 14
  • 23