How to Add New HTML Content using jQuery

How to Add New HTML Content using jQuery

In this article, you will learn How to Add New HTML Content using jQuery. Four jQuery Methods for add new content.

  • append()
  • prepend()
  • after()
  • before()

jQuery append() method

<html>
<head>
<title>jQuery append() Method</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#btn1").click(function(){
    $("p").append(" <b>Appended text</b>.");
  });

  $("#btn2").click(function(){
    $("ol").append("<li>Appended item</li>");
  });
});
</script>
</head>
<body>
<p>paragraph.</p>
<p>another paragraph.</p>
<ol>
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
</ol>
<button id="btn1">Append text</button>
<button id="btn2">Append list items</button>
</body>
</html>

jQuery prepend() Method

<html>
<head>
<title>jQuery prepend() Method</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#btn1").click(function(){
    $("p").prepend("<b>Prepended text</b>. ");
  });
  $("#btn2").click(function(){
    $("ol").prepend("<li>Prepended item</li>");
  });
});
</script>
</head>
<body>
<p>paragraph.</p>
<p>another paragraph.</p>
<ol>
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
</ol>
<button id="btn1">Prepend text</button>
<button id="btn2">Prepend list item</button>
</body>
</html>

jQuery after() and before() Methods

<html>
<title>jquery after() and before() Methods</title>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#btn1").click(function(){
    $("img").before("<b>Before</b>");
  });

  $("#btn2").click(function(){
    $("img").after("<i>After</i>");
  });
});
</script>
</head>
<body>
<img src="img.jpg" alt="jQuery" width="100" height="100"><br><br>
<button id="btn1">Insert before</button>
<button id="btn2">Insert after</button>
</body>
</html>

Read on Facebook

Leave A Reply