How to create a div element in jQuery?

There are many ways to add a div using jQuery, but as the requirement says on click of any square we have to add a div. The following code below will help in adding a div on click ?

Example

Click on any square below to see the result ?

<div id='box'>
    <div class="div" style="background-color:blue;"></div>
    <div class="div" style="background-color:green;"></div>
    <div class="div" style="background-color:red;"></div>
</div>

The jQuery code to create and append a new div element on click ?

$(".div").on("click", function(){
    $('#box').append(
        $('
') .attr("id", "newDiv1") .addClass("div") .append("") .text("hello world") ); });

In this example, we use the $('<div/>') method to create a new div element. We then chain several methods to customize the new element ?

  • .attr("id", "newDiv1") ? Sets the id attribute of the new div
  • .addClass("div") ? Adds a CSS class to the new div
  • .append("<span/>") ? Adds a span element inside the div
  • .text("hello world") ? Sets the text content

Finally, we use .append() to add the newly created div to the container with id 'box'.

Conclusion

Creating div elements dynamically in jQuery is straightforward using the $('<div/>') syntax combined with method chaining to set attributes, classes, and content before appending to the DOM.

Updated on: 2026-03-13T18:56:54+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements