Open In App

Create a Div Element using jQuery

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to create a <div> element using jQuery. We can create a div element with the following steps:

Steps to Create a Div Element

  • Create a new <div> element.
  • Choose a parent element, where to put this newly created element.
  • Put the created div element into the parent element.

Example 1: This example creates a <div> element and uses the append() method to append the element at the end of the parent element.

html




<!DOCTYPE html>
<html>
 
<head>
    <title>
        Create div element using jQuery
    </title>
 
    <script src=
    </script>
 
    <style>
        #parent {
            height: 100px;
            width: 300px;
            background: green;
            margin: 0 auto;
        }
 
        #newElement {
            height: 40px;
            width: 100px;
            margin: 0 auto;
            color: white
        }
    </style>
</head>
 
<body style="text-align:center;">
 
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
 
    <div id="parent"></div>
    <br><br>
 
    <button onclick="insertDiv()">
        Insert Div
    </button>
 
    <!-- Script to insert div element -->
    <script>
        function insertDiv() {
            $("#parent").append('<div id = "newElement">A '
                + 'Computer Science portal for geeks</div>');
        }
    </script>
</body>
 
</html>


Output:

insertDiv

Example 2: This example creates a <div> element and uses prependTo() method to append the element at the start of parent element.

html




<!DOCTYPE html>
<html>
 
<head>
    <title>
        Create div element using jQuery
    </title>
 
    <script src=
    </script>
 
    <style>
        #parent {
            height: 100px;
            width: 300px;
            background: green;
            margin: 0 auto;
        }
 
        #newElement {
            height: 40px;
            width: 100px;
            margin: 0 auto;
            color: white
        }
    </style>
</head>
 
<body style="text-align:center;">
 
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
 
    <div id="parent"></div>
    <br><br>
 
    <button onclick="insertDiv()">
        Insert Div
    </button>
 
    <script>
        function insertDiv() {
            $('<div id = "newElement">A Computer Science portal'
                + ' for geeks</div>').prependTo($('#parent'));
        }
    </script>
</body>
 
</html>


Output:

insertDiv



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads