views:

204

answers:

1

Hi, $('form td .hint p') this jquery selector returns back a list [p,p,p,p,p,p].

I would like to know what's the best way to loop through each of those, check their css values, and do something if the css value = something I want.

I have this function to show and hide a tooltip, but I only want one tooltip to be shown at a time. While doing mouseover and mouseout works, it's buggy because currently I'm using parent(), next(), and child(), to find the right element, and jquery instantaneously inserts a div wrapping around the element I'm showing and hiding. So basically I'm trying to force all other p elements that have display:block to hide every time mouseover occurs.

Currently doing this: target = $('form td .hint p'); target[0].css('display') gives an error.

target.css('display') seems to only return the css of the first one.

Thanks

+5  A: 

Use each():

var displays = '';
$("p").each(function(i, val) {
  displays += "Paragraph " + i + ": " + $(this).css("display") + "\n";
});
alert(displays);

The reason this fails:

var target = $("p");
var display = target[0].css("display");

is that target[0] is not a jQuery object. You could do this:

var display = $(target[0]).css("display");

Also, if you read the documentation for css():

Return a style property on the first matched element.

Two other points worth mentioning.

Firstly, I wouldn't advise doing a tooltip yourself. Get one of the many plugins for this. I've used this one previously and it did the job.

Secondly, if you're checking CSS display values, there may be a shortcut worth using. For instance, you could do this:

$("p").each(function() {
  if ($(this).css("display") == "none") {
    $(this).addClass("blah");
  }
});

but you can also use the :hidden and :visible selectors, so:

$("p:hidden").addClass("blah");

Checking values of css() calls is largely unreliable as you're only checking inline styles and not stylesheet values.

cletus
Hey, actually I just figured out using the :visible selector did the trick. Thanks for the response though, because I need the each() function for something else. Thanks.
Chris
You can use an `each()` function inside of another `each()` function... also you could streamline your selector from `$('form td .hint p')` to `$('.hint p')`. Lastly, please accept cletus' answer. It makes it easier for the people that help to know you found your answer and it will make it more likely that people will help answer your questions - see a 0% accept rate makes people not want to bother reading your question.
fudgey