How do I create a div element in jQuery?
jQuery offers a straightforward way to create HTML elements on the fly. To create a new <div>
element:
// Create a new <div> element with some text var newDiv = $('<div>').text('Hello, world!'); // Append it to the <body> (or any other container) $('body').append(newDiv);
How It Works
$('<div>')
– This creates a jQuery object representing a new<div>
element (not yet added to the DOM)..text('Hello, world!')
– Sets the text content of the newly created<div>
..appendTo('body')
or$('body').append(newDiv)
– Inserts the<div>
into the DOM under the<body>
tag.
Additional Examples
-
Adding multiple attributes:
var fancyDiv = $('<div>', { id: 'myFancyDiv', class: 'fancy-class' }).text('This is a fancy div!'); $('body').append(fancyDiv);
Here,
id
andclass
attributes are set at creation time, making your code more concise. -
Chaining:
$('<div>') .attr('id', 'chainedDiv') .addClass('highlight') .text('Chaining is powerful!') .appendTo('#container');
Each step modifies the same
<div>
object, streamlining your code.
Continue Building Your JavaScript Skills
Mastering jQuery is just one part of being a well-rounded web developer. Strengthen your foundation with:
- Grokking JavaScript Fundamentals – Dive deep into modern JavaScript essentials, from the basics of ES6 to advanced concepts like async/await.
- Grokking the Coding Interview: Patterns for Coding Questions – Discover proven approaches to coding problems that top tech companies frequently test.
For a real-world interview simulation, try Coding Mock Interviews by DesignGurus.io. You’ll gain personalized feedback from ex-FAANG engineers, ensuring you’re ready for anything the interview process throws your way.
In Short
Creating and inserting a <div>
in jQuery is as simple as using '<div>'
inside the $()
function and then appending it to your desired location in the DOM. Combine that with chaining and attribute setting for quick, powerful DOM manipulations.