views:

284

answers:

2

I need to find td within a div and add a class to all the td's within that div, how can I do that with jquery?

+3  A: 
$("#myDiv td").addClass("myClass");
Josh Bush
does it matter if the div is nested within other divs? would i need to chain them?
Nerd Stalker
No, "myDiv" will be the start point for searches no matter how far nested it is.
Josh Bush
+2  A: 

jQuery selectors are based on CSS selectors. a " " (space) inbetween selectors finds all children of the parent node (recursively).

Therefore:

$('#myDiv td')

First finds #mydiv, then get all the descendants (recursively finds the children), and then checks if they are 'td', filtering out the rest.

If you wanted to apply the class just to the immediate children of '#mydiv':

$('#myDiv > td')
Dmitri Farkov
does the <td> need to have a class tag in it already for this to work? Cause it doesn't.
Nerd Stalker
No, tag attributes creation process does not depend on previous existance. to expand on that topic, jquery automatically space delimites multiple classes.
Dmitri Farkov
does it matter if #myDiv is not the parent div id?
Nerd Stalker
It does, because jQuery starts the search from that node, and searches for TD's that are descendants of that node.
Dmitri Farkov