Add Remove HTML Elements Dynamically With Javascript Using JQuery

I was experimenting with some internals of JQuery while writing some simple one or two liner scripts to see how JQuery works. Like any programming language, we all start with a Hello world. So here is my Hello World example using JQuery.


<body>
 <form id="form1" runat="server">
  <div id="content">
  <script type="text/javascript">
  $(function() {
   var v = $("<p>Hello World</p>");
   v.insertAfter("#content");
   });
    
   </script>
   </div>
</form>
</body>

This simple piece of code is inserting a new paragraph HTML element dynamically into document. Translation of the script block is as below:

  • JQuery creates a new paragrah HTML element. If you look at the variable returned by first like of code, it looks as below. You can there is HTMLParagraphElement which is DOM element representing p tag.
  • Next line of code tells jQuery to insert newly created paragraph element after an element that has id of content. JQuery finds that element using well known getElementById and calls DOM method to insert new element dynamically after element with id content.

Simple, isn't it. I will write how this simple piece of code works internally in next post.

Search

Social

Weather

3.9 °C / 38.9 °F

weather conditions Clear

Monthly Posts

Blog Tags