How to select an element that does not exist yet (jQuery) and change its style?

Below is my code. I would like to change the background color of the #preview div, but always failing to select #preview. It doesn't seem to exist when the script is executed. Another jQuery script creates it later.

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

How to select all current and future divs #preview and change their background colors? I think there is something like live (), but I have not yet found an example with changing CSS.

+7
source share
3 answers

jQuery has nothing to do with what you specified. You can add a style element to do this:

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

Like all style rules that will be applied when and when any elements correspond to it. When you add it at the end of a document element, it should win any style conflicts (prohibiting differences in specifics, but id selectors are pretty specific).

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

+7
source

You can not. Basically jQuery nevigate through the DOM tree to select the correct object.

So, run the script after loading the document.

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

#panel or #preview may not exist in your case.

+2
source

live() (which is now deprecated, so use on() instead) for events. Unable to select an item that does not yet exist. However, you can create an element like this:

 var previewDiv = $('<div id="#preview" />'); 

And this div is not yet attached to your document. You can manipulate your CSS as you like:

 previewDiv.css({ 'background-color': good_color }); 

Then your script, which was previously responsible for creating the script, can simply attach it:

 previewDiv.appendTo(parentElement); 
+1
source

All Articles