views:

36

answers:

3

The issue I am having is:

How do I go from a variable pointing at a dom element to using CSS selectors?

I want to make this work:

function highlight(table)
{$(table " > :even").toggleClass('highlight');}

where table is a reference to a table element.

I don't want answers that tell me to use $('#table') because that defeats the point of the generality I am trying to make.

Thanks

+1  A: 

Concatenation.

$(table + " > :even")

DISCLAIMER:

This will only work if the table variable is referencing a String that describes the element. If the variable is actually referencing a DOM element, you would either need to pull the ID out of it before you concatenate, or (better) see Nick Craver's answer.

patrick dw
You can't append a dom element and a string...
Nick Craver
thanks! thats very succinct and readable for jquery developers, if it works, ill try it out
mvrak
+2  A: 

You can do it like this:

function highlight(table) {
  $(table).find("tr:even").toggleClass('highlight');
}

Alternatively you can use '> :even', but be careful because there are <tbody> elements and such to deal with here, unless you have nested tables, the code above is a more resilient approach.

Nick Craver
+1 Thanks for catching my mistake.
patrick dw
@patrick - Depends how you interpret "a variable pointing at an element", I agree it's not completely clear. I take that to mean a DOM element...hopefully the OP will clarify this for us, you may be right, just depends what he meant.
Nick Craver
@Nick - Good point. I think I'll just give a disclaimer in mine, but I've got the feeling it is a reference to an actual element.
patrick dw
Right, I listed ('#table') in the initial description to clarify that. I changed the language a bit too now. Is it clearer?
mvrak
A: 

You can pass a second argument to $() which indicates the context the search should run in:

$("tr:even", table)
Gareth