Reputation: 501
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
Upvotes: 0
Views: 76
Reputation: 138082
You can pass a second argument to $()
which indicates the context the search should run in:
$("tr:even", table)
Upvotes: 0
Reputation: 322502
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.
Upvotes: 1
Reputation: 630429
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.
Upvotes: 2