views:

486

answers:

2

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);
});
A: 

Firstly, if you're cloning elements with IDs, you should really remove or change their ID. Secondly, this should do what you want:

$("#details").clone().removeAttr("id")
  .css({'margin-top':'50px', 'background':'red'})
  .appendTo("#wrapper").children("#details-child")
  .removeAttr("id").css({background: "red"});

Lastly, generally speaking I would recommend using classes rather than raw CSS where possible. Also, if you used class a class like "details" it would more accurately fit the situation (since you have multiple of them) and would be easier to work with.

cletus
Thanks. Can you tell me why I should change or remove their ID's?
FFish
+1  A: 

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.

Alex Sexton
Ok, I forgot to tell... I am using this with SWFObject for alternative content.So the whole #wrapper get's wiped with Flash (if I understand).Than I want to clone the alternative content to render under Flash, with some CSS changes.
FFish
If you want the "alternative content" to render regardless of flash or not, that means it's not "alternative" and you should just move it outside of the container that the flash player may override.
Alex Sexton
Very good point Alex, cheers.
FFish