Append, prepend, after & before in jquery

Append, prepend, after & before in jquery

  • append() – Inserts content at the end of the selected elements
  • prepend() – Inserts content at the beginning of the selected elements
  • after() – Inserts content after the selected elements
  • before() – Inserts content before the selected elements

 

A. append():

<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").append(" <b>Appended text</b>.");
});

$("#btn2").click(function(){
$("ol").append("<li>Appended item</li>");
});
});
</script>


<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>

<button id="btn1">Append text</button>
<button id="btn2">Append list items</button>

 

B. prepend():

$("p").prepend("Some prepended text.");

 

C. before() & after():

<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("img").before("<b>Before</b>");
});

$("#btn2").click(function(){
$("img").after("<i>After</i>");
});
});
</script>

<img src="/images/w3jquery.gif" alt="jQuery" width="100" height="140"><br><br>

<button id="btn1">Insert before</button>
<button id="btn2">Insert after</button>

Leave a Reply