JavaScript Tutorial JavaScript Examples JQuery Tutorial CSS Tutorial HTML Tutorial About Us

Lesson 15 Adding New Content


JQuery can add new content (including HTML markup) to the selected elements using several methods.

The methods are append() , prepend(), before() and after().

15.1 The append() Method

The append() method adds content at the end of the selected elements.

Example 15.1

<!DOCTYPE html>
<html>
<head>
<script>
 $(document).ready(function(){
    $("#btn1").click(function(){
        $("#text1").text("Welcome to jQuery!");
         $("#text2").text("jQuery is fantastic!");
         $("#text3").text("It can enhance your websites!");
    });
});
</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


15.2 The prepend() Method

The prepend() method adds content at the beginning of the selected elements.

Example 15.2

<!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.

  1. apple
  2. banana
  3. orange

15.3 The after() Method

The after() method adds content after the selected elements.

Example 15.3

<!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="http://javascript-tutor.net/jquery/ladybug.gif" style="width:20%;height:auto">

<button id="btn3">Reveal the secret word</button>


</body>
</html>



15.4 The before() Method

The before() method adds content before the selected elements.

Example 15.4

<!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="http://javascript-tutor.net/jquery/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