Reputation: 1144
I have been trying to get this to work for quite some time now.
I am looking for a way to change the background of a div inside a tr onclick with jquery.
What I mean by this is that when the tr (which is named by class) is clicked, then the div with a class name (that is inside the tr) changes color.
The problem that I have been having is that I can set the color of all the divs with the specified class name but not just the one that I clicked it's tr.
I would think the code would look something like this:
$('.backpack_row').click( function(){
if ($(this).css('background-color') != 'rgb(255, 255, 204)')
{
$(this .divClassname).css('background-color', '#000000');
$(this).css('background-color', '#ffffcc');
}
else
{
$(this).css('background-color', '#ffffff');
$(this .divClassname).css('background-color', '#ffffff');
}
});
Here is the HTML:
<table>
<tr class="backpack_row"><td><div class="divClassname"></div></td><td>Other Stuff</td><td></td></tr>
</table>
Thanks, Ian
Upvotes: 1
Views: 638
Reputation: 3279
Your selectors are a bit off, and you're making this harder for yourself. Instead of checking for background colors, check for class existence:
$(".backpack_row").click(function () {
if (!$(this).hasClass("highlighted")) {
$(this).find(".divClassname").addClass("divHighlighted");
$(this).addClass("highlighted");
} else {
$(this).find(".divClassname").removeClass("divHighlighted");
$(this).removeClass("highlighted");
}
});
Upvotes: 1
Reputation: 5461
Try this:
$('.backpack_row').click( function(){
if ($(this).css('background-color') != 'rgb(255, 255, 204)')
{
$(this).find(.divClassname).css('background-color', '#000000');
$(this).css('background-color', '#ffffcc');
}
else
{
$(this).css('background-color', '#ffffff');
$(this).find(.divClassname).css('background-color', '#ffffff');
}
});
You need to use the el.find()
function. It will find an element based on a selector within the el
.
For documentation, here
Upvotes: 0
Reputation: 348962
Fixed your code. A JQuery selector call should be in this format:
$("selector")
$("selector", context)
(where context is this
, in this case) $('.backpack_row').click( function(){
if ($(this).css('background-color') != 'rgb(255, 255, 204)')
{
$(".divClassname", this).css('background-color', '#000000');
$(this).css('background-color', '#ffffcc');
}
else
{
$(this).css('background-color', '#ffffff');
$(".divClassname", this).css('background-color', '#ffffff');
}
Upvotes: 1