Yogesh Ghimire Yogesh Ghimire - 3 months ago 15
jQuery Question

Jquery: unable to figure out why prependTo method of Jquery is not working in this example

I am unable to figure out why the

prependTo
method in the below example is not functioning. I am unable to determine why I am unable to see
"I am new outer div"
text. The following is the code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="js/script.js"></script>
<script type="text/javascript">
$(function(){
var $newDiv = $("<div></div>")
.text("I am new outer div")
.attr("style","color:red");

var $innerDiv = $("<div></div>");
$innerDiv.attr("style","color:green")
.text("I am new inner Div");

var $finalDiv = $innerDiv.prependTo($newDiv)

$("div").append($finalDiv)
})
</script>
</style>
</head>
<body>
<span></span>
<div id="div1" title="My DIV1">DIV1</div>
<div id="div2" title="MY DIV2">DIV2</div>
<h1></h1>
</body>
</html>


The following is the output:

DIV1
I am new inner Div
DIV2
I am new inner Div


I will appreciate your help. Thank you.

Answer

Try this:

$("div").append($newDiv);

The .prependTo() method returns a reference to what you were prepending, so your $finalDiv and $innerDiv both refer to the inner div. So $("div").append($finalDiv.parent()) would also work, but you don't need the $finalDiv variable at all: the $newDiv variable continues to refer to the outer div even after you prepend things to it, and the $innerDiv variable continues to refer to the inner one even after it is prepended.

In context:

$(function(){
  var $newDiv = $("<div></div>")
    .text("I am new outer div")
    .attr("style","color:red");

  var $innerDiv = $("<div></div>");
  $innerDiv.attr("style","color:green")
    .text("I am new inner Div");

  $innerDiv.prependTo($newDiv)

  $("div").append($newDiv)
})
div { border: thin black solid; padding: 5px; margin: 2px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="div1" title="My DIV1">DIV1</div>
<div id="div2" title="MY DIV2">DIV2</div>