Search code examples
jqueryselectcolorselementlive

How to select element that doesn't exist yet (jQuery) and change its style?


Below is my code. I'd like to change background color of #preview div but it always fails to select #preview. It seems that it doesn't exist when script executes. Other jQuery script creates it later on.

jQuery("#panel").mouseleave(function(){
    var good_color = jQuery('.colorpicker_hex input').val();
    jQuery("#preview").css({ 'background-color': good_color });
});

How do I select all current and future #preview divs and change their background colors? I think that there's something like live() but I haven't found example with CSS change yet.


Solution

  • jQuery doesn't specifically have anything to do what you've listed. You can add a style element to do it, though:

    $("<style>#preview { background-color: #eee; }</style>")
        .appendTo(document.documentElement);
    

    Like all style rules, that will apply as and when any elements match it. As you're adding it at the end of the document element, it should win any style conflicts (barring specificity differences, but id selectors are pretty specific).

    Live example - Tested and working in Chrome, Firefox, Opera, IE6, and IE9