JQuery Functions [html-append-prepend]

jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.

these tutrials series will simplify with examples some jquery functions.

.html()

In an HTML document, .html() can be used to get the contents of any element. If the selector expression matches more than one element, only the first match will have its HTML content returned.

The formula : .html( htmlString )

example :

	












	
<!-- HTML -->
<div class="container">
  <div class="box"><p>Demonstration Box</p></div>
</div>
 
<!-- JQuery -->
$('div.box').html('<p>New Demonstration Box</p>');
 
<!-- will result -->
<div class="container">
  <div class="box"><p>New Demonstration Box</p></div>
</div>

the function puts its content ('<p>New Demonstration Box</p>') instead of the matched content ('div.box') which is <div class="box"></div> if exists or create new content if not.

.append()

The .append() method inserts the specified content as the last child of each element in the jQuery collection (To insert it as the first child, use .prepend()).

The formula : .append( content )

example :

	















	
<!-- HTML -->
<div class="container">
  <div class="box"><p>Demonstration Box</p></div>
</div>
 
<!-- JQuery -->
$('div.box').append('<p>New Demonstration Box</p>');
 
<!-- will result -->
<div class="container">
   <div class="box">
     <p>Demonstration Box</p>
     <p>New Demonstration Box</p>
   </div>
   </div>

the function adds its content ('<p>New Demonstration Box</p>') to the end of matched content ('div.box') which is <div class="box"><p>Demonstration Box</p></div>.

.prepend()

The .prepend() method inserts the specified content as the first child of each element in the jQuery collection (To insert it as the last child, use .append()).

The formula : .prepend( content )

example :

















<!-- HTML -->
<div class="container">
  <div class="box"><p>Demonstration Box</p></div>
</div>
 
<!-- JQuery -->
$('div.box').prepend('<p>New Demonstration Box</p>');
 
<!-- will result -->
<div class="container">
   <div class="box">
     <p>New Demonstration Box</p>
     <p>Demonstration Box</p>    
   </div>
  </div>

the function adds its content ('<p>New Demonstration Box</p>') before the matched content ('div.box') which is <div class="box"><p>Demonstration Box</p></div>.

Leave a Comment

Your email address will not be published. Required fields are marked *