Question

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.

Was it helpful?

Solution

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');
});

OTHER TIPS

This should change the background-color:

$('.data_record').css('background-color','#ffffff');
$(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/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top