×

jQuery Tutorial

jQuery Examples

jQuery Practice

jQuery document.createElement equivalent?

In this tutorial, let's see how can we create HTML elements using jQuery which can be done by document.createElement in JavaScript?
Submitted by Pratishtha Saxena, on June 17, 2022

JavaScript method document.createElement() creates a new HTML tag. An HTML tag has to be specified within the brackets. Some text can be passed in the tag using document.createTextNode(). It is then append into the other tags or if not then the body tag of the HTML document using element.appendChild(). This is how createElement() method of JavaScript works.

Now in jQuery, different methods can be used to create DOM elements. Methods like append(), prepend(), after(), before() are used to do the same. As the name suggests, append() method will add the content at the end of the selected HTML element tag, prepend() will add the content at the beginning of the selected tag, after() will add content after the selected element and before() will add content before the selected element in DOM.

Syntax:

$("div").append("Content");
$("div").prepend("Content");
$("p").after("Content");
$("p").before("Content");

Note: Always remember to apply the CDN link while working with jQuery.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Example:

HTML Code:

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Title</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
   </head>
   <body>
      <div id="main">
      </div>
   </body>
</html>

jQuery Function:

<script>
    $(document).ready(function(){
      var h1 = $('<h1>Hello World</h1>')
      h1.attr('style','text-align: center; color: blue')
      $('#main').append(h1)
    })
</script>

Output:

Example: document.createElement equivalent





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.