Search code examples
jquerydynamic-html

How to change the css of a dynamically added element?


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.


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