How to Create a DIV element using jQuery

Creating a div element in jQuery is pretty easy. There are two things you needs to do. Create the div element and then add the element somewhere.

This is the shortest way to create a div element in jQuery

myCustomDiv = $("<div/>");

Using the append or appendTo

A div created this way needs to be put somewhere. You can use the append method of jQuery to do that.


Where parentDiv is the id of the parent division to which you are adding the custom div.

Another way is to use appendTo like shown below


Here the order of the elements are changed but the output remains the same.

To create id and class for the custom div you can pass them as attributes while creating the division,

myCustomDiv = $("<div>", { id:customId, class:customClass, title: customTitle } );

Then you can use append or appendTo like this


Using the prepend or prependTo

You can also use the prepend and prependTo methods to add the newly created division.


Difference between append and prepend

The append method adds the custom division after all the elements in the parent division. And the prepend method adds the custom division before any other element.

If the parent division is empty then append and prepend works the same.