Reputation: 643
I am adding several divs with class "data_record" dynamically to the DOM.
I want each one to turn a colour when clicked and for the others to turn back to a white background.
Here is my code to do this after having successfully added the data_record elements...
$(document).on('click', ".data_record", function(event) {
//turn all others white (this DOES NOT work!)
$('.data_record').css('background','#ffffff');
//turn the clicked element a different colour (this DOES work!)
$(this).css('background', '#EDC580');
});
So how to I target dynamically added elements by their class?
Thanks.
Upvotes: 3
Views: 3793
Reputation: 1803
This should change the background-color
:
$('.data_record').css('background-color','#ffffff');
Upvotes: 2
Reputation: 82231
try using .css('background-color',value)
to set background color:
$(document).on('click', ".data_record", function(event) {
//turn all others white (this now works!)
$('.data_record').css('background-color','#ffffff');
//turn the clicked element a different colour (this DOES work!)
$(this).css('background-color', '#EDC580');
});
Upvotes: 2
Reputation:
$(document).ready(function(){
var n=0;
while(n<10)
{
$("body").append("<div class=dataRecord>Height</div>");
n++;
}
$(".dataRecord").on("click",function(event){
var self=$(this);
$(".dataRecord").css("color","black");
self.css("color","white");
});
Try the fiddle http://jsfiddle.net/sgW77/1/
Upvotes: 1