Question
How can I create a div element using jQuery?
For example, I want to generate a new div in JavaScript with jQuery and then optionally add text, classes, attributes, or insert it into the page.
Short Answer
By the end of this page, you will understand how jQuery creates new DOM elements, how to customize a new div with text, classes, and attributes, and how to append it to the page in a clean, practical way.
Concept
In jQuery, you can create a new HTML element by passing an HTML string to the $() function.
For a div, the most common form is:
$('<div>')
This does not automatically place the element on the page. It creates a jQuery object that wraps a new DOM element in memory. You can then:
- add text with
.text()or HTML with.html() - add classes with
.addClass() - set attributes with
.attr() - insert it into the document with
.append(),.prepend(),.before(), or.after()
This matters because creating elements dynamically is a core part of interactive web development. Real applications often build UI pieces on demand, such as:
- notifications
- cards
- modal content
- list items
- form messages
- API result rows
jQuery makes this process shorter and more readable than using raw DOM methods like document.createElement() and element.appendChild().
Mental Model
Think of jQuery element creation like building a new object in a workshop before placing it in a room.
$("<div>")creates the box.addClass()paints or labels it.text()puts content inside it.appendTo()or.append()moves it into the room
So the element exists first in memory, and only appears on the page after you insert it into the DOM.
Syntax and Examples
Basic syntax
var div = $('<div>');
This creates a new div element as a jQuery object.
Add text and insert it into the page
var div = $('<div>').text('Hello world');
$('body').append(div);
What this does
- creates a new
div - sets its text to
Hello world - appends it to the end of the
body
Add a class and an attribute
var messageBox = $('<div>')
.addClass('message')
.attr('data-type', 'info')
.text('Saved successfully');
$('#container').append(messageBox);
Create the element with attributes immediately
var card = $('<div>', {
class: 'card',
id: 'profile-card',
text: 'User profile'
});
This object form is useful when you want to set several properties at creation time.
Using HTML content
var div = $('<div>').html('<strong>Important:</strong> Read this message.');
$('#container').append(div);
Use .text() when you want plain text. Use .html() only when you intentionally want HTML inside the element.
Step by Step Execution
Consider this example:
var box = $('<div>')
.addClass('notice')
.text('Welcome!');
$('#app').append(box);
Step 1: var box = $('<div>')
A new div element is created in memory.
At this point, it is not yet visible on the page.
Step 2: .addClass('notice')
The class notice is added to that new div.
The element is now equivalent to:
<div class="notice"></div>
Step 3: .text('Welcome!')
The text content is added.
Now the element becomes:
<div class="notice">Welcome!</div>
Step 4: $('#app').append(box)
The new element is inserted inside the element with id app.
If the page contains:
<div id="app"></div>
it becomes:
<div id="app">
<div class="notice">Welcome!</div>
</div>
That final step is what makes the element appear in the document.
Real World Use Cases
Dynamic element creation in jQuery is commonly used for:
- Notifications: create success or error messages after a form submission
- Search results: build result cards from API data
- Comments or chat messages: add new entries without reloading the page
- Validation feedback: insert error
divs near invalid form fields - Dashboard widgets: generate panels based on user settings
- Loading states: create temporary status boxes like
Loading...
Example: showing an error message after failed validation
var errorBox = $('<div>')
.addClass('error-message')
.text('Email is required');
$('#email-field').after(errorBox);
Example: adding items from an API response
var userCard = $('<div>').addClass('user-card');
userCard.text('Alice Johnson');
$('#users').append(userCard);
Real Codebase Usage
In real projects, developers rarely create a div with no follow-up steps. Usually the element is part of a pattern.
Common patterns
1. Create, configure, insert
var alertBox = $('<div>')
.addClass('alert alert-success')
.text('Profile updated');
$('#messages').append(alertBox);
2. Guard clause before creating UI
if (!user.name) {
return;
}
var card = $('<div>').addClass('user-card').text(user.name);
$('#list').append(card);
This avoids creating incomplete elements when required data is missing.
3. Build repeated elements in loops
users.forEach(function(user) {
var item = $('<div>').addClass('user').text(user.name);
$('#users').append(item);
});
4. Use helper functions
function createMessage(text, type) {
return $('<div>')
.addClass('message ' + type)
.text(text);
}
$('#messages').append(createMessage('Saved', 'success'));
This makes code easier to reuse and maintain.
5. Safe text insertion
Developers often prefer .text() over .html() for user-provided values to avoid accidentally rendering unsafe HTML.
var comment = $('<div>').text(userComment);
Common Mistakes
1. Forgetting to insert the element into the DOM
This creates the element, but it will not appear on the page:
var div = $('<div>').text('Hello');
You still need to append it somewhere:
$('body').append(div);
2. Mixing jQuery objects and raw DOM elements incorrectly
Broken example:
var div = $('<div>');
div.appendChild(document.createTextNode('Hello'));
appendChild() is a DOM method, not a jQuery method.
Correct jQuery version:
var div = $('<div>').text('Hello');
Or use the raw DOM element:
var div = $('<div>')[0];
div.appendChild(document.createTextNode('Hello'));
3. Using .html() when .text() is safer
var div = $('<div>').html(userInput);
If userInput comes from users, this may insert unintended HTML.
Safer option:
var div = $('<div>').text(userInput);
4. Writing invalid HTML strings
Broken example:
var div = $('<div');
Correct:
var div = $('<div>');
5. Assuming $('<div>') selects existing elements
$('<div>')
This creates a new element.
$('div')
This selects existing div elements already in the document.
Comparisons
| Approach | Example | What it does | When to use |
|---|---|---|---|
| jQuery create element | var div = $('<div>'); | Creates a new element wrapped in a jQuery object | Best when working in jQuery code |
| jQuery select existing elements | var divs = $('div'); | Selects existing div elements in the page | When you want to read or modify current elements |
| DOM createElement | var div = document.createElement('div'); | Creates a raw DOM element | Useful in plain JavaScript without jQuery |
jQuery .text() | div.text('Hello') | Inserts plain text | Best for safe text content |
jQuery .html() | div.html('<b>Hello</b>') | Inserts HTML content | Use only when HTML is intentional |
jQuery vs plain JavaScript
// jQuery
var div = $('<div>').addClass('box').text('Hello');
$('body').append(div);
// Plain JavaScript
var div = document.createElement('div');
div.className = 'box';
div.textContent = 'Hello';
document.body.appendChild(div);
jQuery is shorter and chains nicely. Plain JavaScript does not require the jQuery library.
Cheat Sheet
// Create a div
var div = $('<div>');
// Create and add text
var div = $('<div>').text('Hello');
// Create and add HTML
var div = $('<div>').html('<strong>Hello</strong>');
// Add class
var div = $('<div>').addClass('box');
// Add attribute
var div = $('<div>').attr('id', 'my-box');
// Create with options
var div = $('<div>', {
class: 'box',
id: 'my-box',
text: 'Hello'
});
// Insert into page
$('body').append(div);
$('#container').prepend(div);
$('#target').before(div);
$('#target').after(div);
// Append directly
$('<div>').text('Hello').appendTo('body');
Key rules
$("<div>")creates a new element$("div")selects existing elements.text()adds plain text.html()adds HTML- The element appears only after insertion into the DOM
FAQ
How do I create a div in jQuery?
Use:
var div = $('<div>');
How do I add text to a newly created div?
Use .text():
var div = $('<div>').text('Hello');
How do I append a created div to the page?
Use .append() or .appendTo():
$('body').append(div);
What is the difference between $('div') and $('<div>')?
$('div')selects existingdivelements$('<div>')creates a newdiv
Can I create a div with a class in jQuery?
Yes:
var div = $('<div>').addClass('box');
or:
var div = $('<div>', { class: 'box' });
Should I use .text() or .html()?
Use .text() for plain content, especially user input. Use .html() only when you intentionally want to insert HTML.
Does creating an element automatically show it on the page?
No. You must insert it into the DOM with methods like .append() or .appendTo().
Mini Project
Description
Build a small notification area that creates new div messages with jQuery and adds them to the page when buttons are clicked. This demonstrates creating elements, adding classes and text, and inserting them into the DOM.
Goal
Create reusable jQuery code that generates success and error message div elements and displays them inside a container.
Requirements
- Create a container where messages will appear.
- Add one button for a success message and one button for an error message.
- When a button is clicked, create a new
divwith the correct text and class. - Insert each new message into the page using jQuery.
- Keep the code readable by using a helper function.
Keep learning
Related questions
Add a Favicon to a Static HTML Page
Learn how to add a favicon to static HTML pages, use correct paths and icon formats, and troubleshoot browser caching and local-file issues.
Allow Only Numeric Input (0-9) in HTML Input Using jQuery
Learn how to allow only digits 0-9 in an HTML input using jQuery, with examples, validation tips, common mistakes, and best practices.
Apply CSS !important with jQuery .css()
Learn why jQuery .css() cannot set !important and how to use CSSStyleDeclaration.setProperty() to apply inline important styles safely.