Coder Perfect

Using jQuery to make a div element [duplicate]

Problem

In jQuery, how do I make a div element?

Asked by useranon

Solution #1

You can now provide attributes to a self-closed element in jQuery 1.4, like follows:

jQuery('<div>', {
    id: 'some-id',
    class: 'some-class some-other-class',
    title: 'now this div has a title!'
}).appendTo('#mySelector');

It’s in the Docs now.

jQuery 1.4 Released: jQuery 1.4 Released: jQuery 1.4 Released: jQuery 1.4 Released: The 15 New Features You Should Be Aware Of

Answered by ian

Solution #2

You can append (to add at the end of the parent) or prepend (to add at the beginning of the parent):

$('#parent').append('<div>hello</div>');    
// or
$('<div>hello</div>').appendTo('#parent');

Alternatively, as suggested in a different answer, you can use the.html() or.add() functions.

Answered by cm2

Solution #3

Technically $(”) will ‘create’ a div element (or more specifically a DIV DOM element) but won’t add it to your HTML document. You’ll need to combine that with the other answers to accomplish anything helpful with it (like using the add() technique or something similar).

The manipulation documentation explains all of the different ways to add new elements.

Answered by samjudson

Solution #4

d = document.createElement('div');
$(d).addClass(classname)
    .html(text)
    .appendTo($("#myDiv")) //main div
.click(function () {
    $(this).remove();
})
    .hide()
    .slideToggle(300)
    .delay(2500)
    .slideToggle(300)
    .queue(function () {
    $(this).remove();
});

Answered by celoron

Solution #5

div = $("<div>").html("Loading......");
$("body").prepend(div);    

Answered by Ish

Post is based on https://stackoverflow.com/questions/867916/creating-a-div-element-in-jquery