How to Create DOM Elements with jQuery $()
Creating DOM elements dynamically is a core feature of jQuery that
allows developers to generate and manipulate HTML on the fly. By passing
an HTML string or element definition into the global jQuery function,
$(), you can instantly instantiate new elements in memory,
configure their attributes, events, and styling, and append them
directly to the webpage. This guide explains how to generate elements
using basic HTML strings, configure them using attributes objects, and
insert them into the active document.
Basic Syntax: Using HTML Strings
To create an element on the fly, pass a string containing valid HTML
markup directly into the $() function. jQuery recognizes
the HTML syntax and creates the corresponding DOM node in memory.
// Create a simple div
const $newDiv = $("<div></div>");
// Self-closing tags can be written compactly
const $newParagraph = $("<p>");You can also include nested elements, text, and attributes directly inside the string:
const $card = $('<div class="card"><h2>Title</h2><p>Content</p></div>');Adding Attributes, Content, and Events Simultaneously
Instead of writing a long HTML string, jQuery allows you to pass a tag name as the first argument and a JavaScript object containing attributes, properties, and event listeners as the second argument.
const $button = $("<button>", {
id: "submit-btn",
class: "btn btn-primary",
text: "Click Me",
click: function () {
alert("Button clicked!");
},
});This method improves readability and dynamically binds handlers directly to the newly instantiated element.
Modifying Elements via Chaining
Once an element is created, you can use standard jQuery chaining methods to configure it further before placing it in the DOM:
const $alert = $("<div>")
.addClass("alert alert-warning")
.text("This is an alert message.")
.css("display", "none");Inserting the Element into the DOM
Creating an element with $() keeps it in memory until
you explicitly attach it to the Document Object Model. Use DOM insertion
methods to place the element where needed:
append()/appendTo(): Inserts the element at the end inside a target container.prepend()/prependTo(): Inserts the element at the beginning inside a target container.after()/insertAfter(): Inserts the element immediately following a target sibling.before()/insertBefore(): Inserts the element immediately preceding a target sibling.
// Create the element
const $item = $("<li>", {
class: "list-group-item",
text: "Dynamic List Item",
});
// Append it to an existing list
$("#my-list").append($item);
// Alternatively, use appendTo
$item.appendTo("#my-list");