jQuery can add new content (including HTML markup) to the selected elements using several methods.
The methods are append() , prepend(), before() and after().
The append() method adds content at the end of the selected elements.
<!DOCTYPE html> <html> <head> <script> $(document).ready(function(){ $("#btn1").click(function(){ $("#text1").append(" clever and cute"); $("#text2").append("<b>nice but very strict</b>"); $("#lt1").append("<i> apple</i>"); $("#lt2").append("<i> banana</i>"); $("#lt3").append("<i> orange</i>"); }); }); </script> </head> <body> <p id="text1">This boy is </p> <p id="text2">The teacher is </p> <ul> <li id="lt1">Item 1 is</li> <li id="lt2">Item 2 is</li> <li id="lt3">Item 3 is</li> </ul> <button id="btn1">Add New Content</button> </body> </html>
This boy is
The teacher is
The prepend() method adds content at the beginning of the selected elements.
<!DOCTYPE html> <html> <head> <script> $(document).ready(function(){ $("#btn2").click(function(){ $("#text3").prepend("The boys are "); $("#text4").prepend("<b>The teacher is </b>"); $("#li1").prepend("<i>I like </i>"); $("#li2").prepend("<i>He likes </i>"); $("#li3").prepend("<i>She like </i>"); }); }); </script> </head> <body> <p id="text3">clever and cute.</p> <p id="text4">nice but strict.</p> <ol> <li id="li1">apple</li> <li id="li2">banana</li> <li id="li3">orange</li> </ol> <button id="btn2">Append New Content</button> </body> </html>
clever and cute.
nice but strict.
The after() method adds content after the selected elements.
<!DOCTYPE html> <html> <head> <script> $(document).ready(function(){ $("#btn3").click(function(){ $("#Img1").after("<b>I am the ladybug!</b>"); }); }); </script> </head> <body> <img id="Img1" src="https://javascript-tutor.netjQuery/ladybug.gif" style="width:20%;height:auto"> <button id="btn3">Reveal the secret word</button> </body> </html>
The before() method adds content before the selected elements.
<!DOCTYPE html> <html> <head> <script> $(document).ready(function(){ $("#btn4").click(function(){ $("#Img2").before("<b>I am the ladybug!</b>"); }); }); </script> </head> <body> <img id="Img2" src="https://javascript-tutor.netjQuery/ladybug.gif" style="width:20%;height:auto"> <button id="btn4">Reveal the secret word</button> </body> </html>
Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy