Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 992
Atadj Avatar asked Jan 19 '12 11:01

Atadj


People also ask

Can you use CSS selectors in jQuery for selecting elements?

jQuery uses CSS-style selectors to select parts, or elements, of an HTML page. It then lets you do something with the elements using jQuery methods, or functions. To use one of these selectors, type a dollar sign and parentheses after it: $() . This is shorthand for the jQuery() function.

How do you select an element with a particular class Sselected?

How to select element having a particular class (". selected")? Ans: $('. selected').

Which is the jQuery selector function used for selecting the elements?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.


2 Answers

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

like image 70
T.J. Crowder Avatar answered Oct 01 '22 19:10

T.J. Crowder


You can not. Basically jQuery nevigate via DOM tree to select proper object.
So, run script after document loaded.

$(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 might not exist in your case.

like image 42
Sang Avatar answered Oct 01 '22 21:10

Sang