Search code examples
jquerycsshtmlclone

Jquery change CSS of child div after clone


After I clone a DIV and can change it's CSS properties, but can't find how to change it's child DIV's CSS. In the following example I want to change the background of #details-child from yellow to blue. CSS:

#wrapper {
    width:200px;
    background:gray;
}
#details {
    width:200px;
    height:100px;
    background:green;
}
#details-child {
    width:100px;
    height:100px;
    background:yellow;
}

JS:

jQuery.noConflict();
jQuery(document).ready(function() {
    // clone
        clone_details = jQuery("#details").clone();

    // change CSS           
        clone_details.css({'margin-top':'50px', 'background':'red'});
        // jQuery("#details-child").css('background','blue'); // changes original div

    // render clone
        jQuery("#wrapper").append(clone_details);
});

Solution

  • Once you have a jquery object, you can do a selector search from within the scope of that object with $.find()

    http://api.jquery.com/find/

    clone_details.find('#details-child').something();

    However, you don't want to end up with duplicated IDs everywhere, so I'd suggest you move to using classes instead of IDs, since those have to be unique.