tags:

views:

64

answers:

4

Hello Everyone, How would i go about adding a class to a td tag given the following table:

<table>
    <tr>
        <td id="1"></td>
        <td id="2"></td>
        <td id="3"></td>
    </tr>
</table>

I would like to add the class to the td with the id of 2. The class name in my case is td_highlight.

Have tried a few different scripts with no luck.

Thanks in advance, Billy

+3  A: 
$('#2').addClass('td_highlight');

I am not including td in the selector because all your ids (by definition) should be unique in the page.

see the relevant bit of documentation for further reference.

JohnIdol
Thanks for the quick response.
Billy Logan
u welcome - keep in mind @edl considerations about the ids though
JohnIdol
A: 

You can use the addClass() function:

$('td#2').addClass('td_highlight');
spad3s
A: 

jQuery('td#2').addClass('class');

sushil bharwani
This is a dumb comment, but I felt compelled to at least bring it up. Using the tagName#id approach breaks jQuery's internal mapping to getElementByID thusly slowing down the query. Not a huge deal in this case tho...
lark
if this is the case thanks for bringing it up; I never knew that
sushil bharwani
+10  A: 

you can use $('#2').addClass('td_highlight'); However, using a numerical value for an id may not play nice with some browsers. According to W3c:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

You might try looking at: http://www.w3.org/TR/html4/types.html

edl
+1 good catch with id naming rules
JohnIdol