One of the cool features of Jquery library is write less and do more. Yes it is true,There are so many handy methods are available for doing much functionalities with few line of code. Now for adding new element in jquery is very simple, we can do using following methods
1. append() : used for inserting the element at end of the content.
2. prepend() : used for inserting the element at beging of the content.
3. after() : used for inserting the element after the selected elements.
4. before(): used to inserting the element before the selected element.
Sample code for all add Methods:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="../../Scripts/jquery.min.js"></script> <style type="text/css"> body { padding: 50px; } .target { border: 2px solid #bbb; background-color: #eee; padding: 10px; margin: 10px auto; } .child { display: block; width: 65px; font: bold 12px Arial,Sans-Serif; color: white; padding: 5px 10px; background-color: green; } .sibling { display: block; width: 70px; font: bold 12px Arial,Sans-Serif; color: white; padding: 5px 10px; background-color: blue; } </style> <script> $(function () { $("#btnSum").click(function () { $('.target') .append('<div class="child">1. Append</div>') .prepend('<div class="child">2. Prepend</div>') .before('<div class="sibling">3. Before</div>') .after('<div class="sibling">4. After</div>'); }); }); </script> </head> <body> <fieldset> <legend> <b>Sample code for all Add methods of Jquery </b> </legend> <div class="target">This is the target div to which new elements are associated using jQuery</div> <br /> <button id="btnSum">Click Here</button> </fieldset> </body> </html>
For removing element from Jquery there are the following methods
1. remove(): Used to remove the selected element
2. empty() : used to remove the child elements from selected elements.
Sample code
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="../../Scripts/jquery.min.js"></script> <script> $(function () { $("#btnRemove").click(function () { $("#div1").remove(); }); $("#btnEmpty").click(function () { $("#div2").empty(); }); }); </script> </head> <body> <fieldset style="width:500px;"> <legend><b>Sample code for removing Div element</b></legend> <div id="div1" style="background-color:green;border:solid 1px;"> <p>This is the text in Div Element.</p> </div> <br /> <button id="btnRemove">Click Here to remove element</button> </fieldset> <br /> <fieldset style="width:500px;"> <legend><b>Sample code for Empty Div elemnt </b></legend> <div id="div2" style="background-color:green;border:solid 1px; height:100px;"> <p>This is the text in Div Element.</p> </div> <br /> <button id="btnEmpty">Click Here to empty element</button> </fieldset> </body> </html>
OP for before click
OP after click event
Summary
In the above example we showed that how to add and remove html element using Jquery Methods.
One thought on “Add and remove element in Jquery (Part 9)”