I want to change the class of a td tag given the td tag's id:
<td id="td_id" class="change_me"> ...
I want to be able to do this while inside the click event of some other dom object. How do I grab the td's id and change its class?
I want to change the class of a td tag given the td tag's id:
<td id="td_id" class="change_me"> ...
I want to be able to do this while inside the click event of some other dom object. How do I grab the td's id and change its class?
You can set the class (regardless of what it was) by using .attr()
, like this:
$("#td_id").attr('class', 'newClass');
If you want to add a class, use .addclass()
instead, like this:
$("#td_id").addClass('newClass');
Or a short way to swap classes using .toggleClass()
:
$("#td_id").toggleClass('change_me newClass');
Here's the full list of jQuery methods specifically for the class
attribute.
EDIT:
If you're saying that you're changing it from a nested element, you don't need the ID at all. You can do this instead:
$(this).closest('td').toggleClass('change_me some_other_class');
//or
$(this).parents('td:first').toggleClass('change_me some_other_class');
Original answer:
$('#td_id').removeClass('change_me').addClass('some_other_class');
Another option is:
$('#td_id').toggleClass('change_me some_other_class');
I think you're looking for this:
$('#td_id').removeClass('change_me').addClass('new_class');
So you want to change it WHEN it's clicked...let me go through the whole process. Let's assume that your "External DOM Object" is an input, like a select:
Let's start with this HTML:
<body>
<div>
<select id="test">
<option>Bob</option>
<option>Sam</option>
<option>Sue</option>
<option>Jen</option>
</select>
</div>
<table id="theTable">
<tr><td id="cellToChange">Bob</td><td>Sam</td></tr>
<tr><td>Sue</td><td>Jen</td></tr>
</table>
</body>
Some very basic CSS:
#theTable td {
border:1px solid #555;
}
.activeCell {
background-color:#F00;
}
And set up a jQuery event:
function highlightCell(useVal){
$("#theTable td").removeClass("activeCell")
.filter(":contains('"+useVal+"')").addClass("activeCell");
}
$(document).ready(function(){
$("#test").change(function(e){highlightCell($(this).val())});
});
Now, whenever you pick something from the select, it will automatically find a cell with the matching text, allowing you to subvert the whole id-based process. Of course, if you wanted to do it that way, you could easily modify the script to use IDs rather than values by saying
.filter("#"+useVal)
and make sure to add the ids appropriately. Hope this helps!