In this post, Â we are going to see jQuery prepend and prependTo methods.
Live demo:
JS Bin on jsbin.com
Both do the same task, insert text or html before content of every selected elements, so it will put text or html to first index of selected element. Both methods add text or html as a child to selected elements .Syntax is quite different for for prepend and prepend to nethod.
Syntax for prepend() :
1 2 3 4 5 |
$("selectors").prepend("element to be inserted") Example : $("div").prepend(" |
inserting using prepend
1 2 3 |
"); |
Syntax for prependTo() :
1 2 3 4 5 |
$("element to be inserted") .prependTo("div"); Example: $(" |
inserting using prependTo
1 2 3 |
").prependTo("div"); |
Let’s understand with the help of example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
<title>Jquery prepend and prependTo example </title> <script src="http://code.jquery.com/jquery-2.2.3.min.js"></script> <h2>Jquery prepend and prependTo example</h2> <style> .red{ border:3px dotted red; color:red; font-family: arial narrow; } .blue{ border:3px dotted red; color:blue; font-family: arial narrow; } .blackBorder{ border:4px dotted black; </style> <script type="text/javascript"> $(document).ready(function(){ $("#prependButton").click(function(){ $("div").prepend("<p class='red'>inserting using prepend"); }); $("#prependToButton").click(function(){ $("<p class='blue'>inserting using prependTo").prependTo("div"); }); $("#reset").click(function(){ location.reload(); }); }); </script> <button id="prependButton">Using prepend</button> <button id="prependToButton">Using prependTo</button> <button id="reset">Reset</button> <div class="blackBorder"> Hello world from java2blog!!!! </div> <br> <div class="blackBorder"> Welcome to JQuery. </div> |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.