When I click on the anchor tag, the image shifts from div#left
to div#right
. I want the image to be copied. Is this the default behaviour of prepend()
? How can I avoid this problem?
The image is just a placeholder for a big div with many children.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="Scripts/JavaScript.js"></script>
</head>
<body>
<div id="left" style="float:left">
<img src="Images/Rooms/K1.jpg" alt="Alternate Text" height="200" width="200"/>
</div>
<div id="right" style="float:right"></div>
<a id="addImageToRight" href="#">Add Image toRight</a>
</body>
</html>
The jQuery is:
$(document).ready(function () {
$("#addImageToRight").click(function () {
var $image = $("#left img");
var imgCopy = $image;
$("div#right").prepend(imgCopy);
});
});
prepend() method inserts the specified content as the first child of each element in the jQuery collection (To insert it as the last child, use . append() ).
prepend() The Element. prepend() method inserts a set of Node objects or string objects before the first child of the Element . String objects are inserted as equivalent Text nodes.
prepend() .append() puts data inside an element at the last index; while. . prepend() puts the prepending element at the first index.
1) Using the prepend() method to prepend an element example First, select the ul element by its id by using the querySelector() method. Second, declare an array of strings. Third, for each element in an array, create a new li element with the textContent is assigned to the array element.
Is this the default behaviour of prepend()?
Yes. Putting a DOM node somewhere in the document requires removing it from wherever in the document it is already. It can't exist in two places at the same time.
var imgCopy = $image;
That copies the value of $image
to imgCopy
. The value is a reference to the object. (In JavaScript, variables can only every hold references to objects).
How to avoid this problem?
Create a copy of the DOM node. Call .clone()
on the jQuery object and prepend the return value.
var imgCopy = $image.clone();
You need to update your code from
var $image = $("#left img");
var imgCopy = $image;
to
var imgCopy = $("#left img").clone();
For reference - http://plnkr.co/edit/R5yjTY06dKkqccwmxS62?p=preview
Perhaps take a look at jQuery's clone() to create a copy of the img element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With