Logo

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

  1. $('<div>') – This creates a jQuery object representing a new <div> element (not yet added to the DOM).
  2. .text('Hello, world!') – Sets the text content of the newly created <div>.
  3. .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 and class 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:

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.

CONTRIBUTOR
TechGrind