views:

45

answers:

2

Hi

I have a little problem when i try to clone an element with jquery basically I Have this, i want to clone the div called clone and put in other div in some where else.

<li class="jqModal"  >
    <div class="clone">
    <div class="image">
            <img src="<?php echo $products[$j]['thumb']; ?>"
                 title="<?php echo $products[$j]['name']; ?>" alt="<?php echo $products[$j]['name']; ?>" />
    </div>
    <h2><a href=""><?php echo $products[$j]['name']; ?></a></h2>
    <strong class="price"><?php echo $products[$j]['price']; ?></strong>
    <a href="<?php echo $products[$j]['href']; ?>">More details</a>
    </div>


</li>`

I use this in my document ready

$(document).ready(function () {
   $(".product-list li").hover(
      function () {
         //replace image and id
         $var = $(this).clone(false).find("#clone").
         $('#div-to-replace').replaceWith($var);
      }
   );
});

But its not working any advice, thank you in advance. :)

A: 

Try this:

$(".product-list li").hover(
    function () {
        //replace image and id
        $var = $('.clone', this).clone();
        $('#div-to-replace').replaceWith($var);
    }
);

Changes to your code:

  1. You want to clone the element with the class "clone", not the id: #clone -> .clone
  2. If you clone first and then find the element, then you're cloning too much, so I changed the selector for cloning
  3. At the end of this line there's a dot where should be a semicolon.​
Dave
+1  A: 

There are 3 problems that I see here, first this line:

$var = $(this).clone(false).find("#clone").

You need a ; at the end instead of a . so you don't get a syntax error, and also clone is the class not the #ID, so you need .find('.clone'). Then here:

$('#div-to-replace').replaceWith($var);

That <div> you're replacing would be totally gone, so it wouldn't work next time around, I think what you want is this:

var product = $(this).find('.clone').clone();
$('#div-to-replace').empty().append(product);

This doesn't replace the #div-to-replace but instead puts the content in there, otherwise you would be missing the <div> when you hovered the next product. Also be sure to use var when creating local variables so it doesn't product unwanted side-effects with the global variable you get without it :)

Nick Craver