Creating a div element in jQuery [duplicate]
Asked Answered
S

24

1649

How do I create a div element in jQuery?

Selfdrive answered 15/5, 2009 at 10:30 Comment(4)
See: What is the most efficient way to create HTML elements using jQuery?Johannejohannes
$(document.createElement('DIV'))Evanesce
$('#parent').append('<div>hello</div>'); // or $('<div>hello</div>').appendTo('#parent');Laryngo
$('#parent').append($('<div>').html('your content'));Sentimentality
E
1162

You can use append (to add at last position of parent) or prepend (to add at fist position of parent):

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

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

Egestion answered 15/5, 2009 at 10:43 Comment(0)
R
2091

As of jQuery 1.4 you can pass attributes to a self-closed element like so:

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

Here it is in the Docs

Examples can be found at jQuery 1.4 Released: The 15 New Features you Must Know .

Rafe answered 11/11, 2010 at 19:1 Comment(1)
This option looks cleaner, but seems like the data attribute is not supported due to the dash sign, e.g. data-something.Cravens
E
1162

You can use append (to add at last position of parent) or prepend (to add at fist position of parent):

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

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

Egestion answered 15/5, 2009 at 10:43 Comment(0)
M
241

Technically $('<div></div>') will 'create' a div element (or more specifically a DIV DOM element) but won't add it to your HTML document. You will then need to use that in combination with the other answers to actually do anything useful with it (such as using the append() method or such like).

The manipulation documentation gives you all the various options on how to add new elements.

Monetta answered 15/5, 2009 at 10:49 Comment(0)
F
208
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();
});
Fritts answered 7/8, 2011 at 22:8 Comment(0)
D
83
div = $("<div>").html("Loading......");
$("body").prepend(div);    
Dentilingual answered 15/5, 2009 at 10:36 Comment(0)
F
69
$("<div/>").appendTo("div#main");

will append a blank div to <div id="main"></div>

Feigned answered 15/5, 2009 at 10:34 Comment(0)
F
61

A short way of creating div is

var customDiv = $("<div/>");

Now the custom div can be appended to any other div.

Frau answered 25/2, 2015 at 3:46 Comment(0)
S
57

All these worked for me,

HTML part:

<div id="targetDIV" style="border: 1px solid Red">
    This text is surrounded by a DIV tag whose id is "targetDIV".
</div>

JavaScript code:

//Way 1: appendTo()
<script type="text/javascript">
    $("<div>hello stackoverflow users</div>").appendTo("#targetDIV"); //appendTo: Append at inside bottom
</script>

//Way 2: prependTo()
<script type="text/javascript">
    $("<div>Hello, Stack Overflow users</div>").prependTo("#targetDIV"); //prependTo: Append at inside top
</script>

//Way 3: html()
<script type="text/javascript">
    $("#targetDIV").html("<div>Hello, Stack Overflow users</div>"); //.html(): Clean HTML inside and append
</script>

//Way 4: append()
<script type="text/javascript">
    $("#targetDIV").append("<div>Hello, Stack Overflow users</div>"); //Same as appendTo
</script>
Simian answered 28/1, 2011 at 4:41 Comment(0)
T
43
$("<div/>").attr('id','new').appendTo('body');    

This will create new div with id "new" into body.

Tove answered 3/2, 2012 at 15:56 Comment(0)
H
28
document.createElement('div');
Hodge answered 17/6, 2011 at 12:15 Comment(0)
M
22

Create an in-memory DIV

$("<div/>");

Add click handlers, styles etc - and finally insert into DOM into a target element selector:

$("<div/>", {

  // PROPERTIES HERE
  
  text: "Click me",
  id: "example",
  "class": "myDiv",      // ('class' is still better in quotes)
  css: {           
    color: "red",
    fontSize: "3em",
    cursor: "pointer"
  },
  on: {
    mouseenter: function() {
      console.log("PLEASE... "+ $(this).text());
    },
    click: function() {
      console.log("Hy! My ID is: "+ this.id);
    }
  },
  append: "<i>!!</i>",
  appendTo: "body"      // Finally, append to any selector
  
}); // << no need to do anything here as we defined the properties internally.
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Similar to ian's answer, but I found no example that properly addresses the use of methods within the properties object declaration so there you go.

Monitorial answered 1/5, 2017 at 13:5 Comment(0)
C
19

Here's another technique for creating divs with jQuery.

ELEMENT CLONING

Say you have an existing div in your page that you want to clone using jQuery (e.g. to duplicate an input a number of times in a form). You would do so as follows.

$('#clone_button').click(function() {
  $('#clone_wrapper div:first')
  .clone()
  .append('clone')
  .appendTo($('#clone_wrapper'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clone_wrapper">
  <div>
    Div
  </div>
</div>

<button id="clone_button">Clone me!</button>
Cosma answered 27/11, 2012 at 13:16 Comment(0)
J
9

simply if you want to create any HTML tag you can try this for example

var selectBody = $('body');
var div = $('<div>');
var h1  = $('<h1>');
var p   = $('<p>');

if you want to add any element on the flay you can try this

selectBody.append(div);
Jung answered 14/10, 2016 at 5:29 Comment(0)
B
8
<div id="foo"></div>

$('#foo').html('<div></div>');
Brosine answered 15/5, 2009 at 10:34 Comment(1)
In case existing div (id="foo") already contains some element(s) this technique will replace them with new empty div.Rockhampton
C
8

alternatively to append() you can also use appendTo() which has a different syntax:

$("#foo").append("<div>hello world</div>");
$("<div>hello world</div>").appendTo("#foo");    
Contradiction answered 31/8, 2016 at 7:58 Comment(0)
L
7

If you are using Jquery > 1.4, you are best of with Ian's answer. Otherwise, I would use this method:

This is very similar to celoron's answer, but I don't know why they used document.createElement instead of Jquery notation.

$("body").append(function(){
        return $("<div/>").html("I'm a freshly created div. I also contain some Ps!")
            .attr("id","myDivId")
            .addClass("myDivClass")
            .css("border", "solid")                 
            .append($("<p/>").html("I think, therefore I am."))
            .append($("<p/>").html("The die is cast."))
});

//Some style, for better demonstration if you want to try it out. Don't use this approach for actual design and layout!
$("body").append($("<style/>").html("p{background-color:blue;}div{background-color:yellow;}div>p{color:white;}"));

I also think using append() with a callback function is in this case more readable, because you now immediately that something is going to be appended to the body. But that is a matter of taste, as always when writing any code or text.

In general, use as less HTML as possible in JQuery code, since this is mostly spaghetti code. It is error prone and hard to maintain, because the HTML-String can easily contain typos. Also, it mixes a markup language (HTML) with a programming language (Javascript/Jquery), which is usually a bad Idea.

Liven answered 14/3, 2016 at 11:40 Comment(0)
C
5

You can create separate tags using the .jquery() method. And create child tags by using the .append() method. As jQuery supports chaining, you can also apply CSS in two ways. Either specify it in the class or just call .attr():

var lTag = jQuery("<li/>")
.appendTo(".div_class").html(data.productDisplayName);

var aHref = jQuery('<a/>',{         
}).appendTo(lTag).attr("href", data.mediumImageURL);

jQuery('<img/>',{                                               
}).appendTo(aHref).attr("src", data.mediumImageURL).attr("alt", data.altText);

Firstly I am appending a list tag to my div tag and inserting JSON data into it. Next, I am creating a child tag of list, provided some attribute. I have assigned the value to a variable, so that it would be easy for me to append it.

Calc answered 26/8, 2013 at 7:3 Comment(1)
"JQuery('<a />', {})" Why are you supplying an empty object?Sample
S
2

I think this is the best way to add a div:

To append a test div to the div element with ID div_id:

$("#div_id").append("div name along with id will come here, for example, test");

Now append HTML to this added test div:

$("#test").append("Your HTML");
Shoot answered 16/2, 2012 at 8:52 Comment(0)
M
2

I hope that helps code. :) (I use)

function generateParameterForm(fieldName, promptText, valueType) {
    //<div class="form-group">
    //<label for="yyy" class="control-label">XXX</label>
    //<input type="text" class="form-control" id="yyy" name="yyy"/>
    //</div>

    // Add new div tag
    var form = $("<div/>").addClass("form-group");

    // Add label for prompt text
    var label = $("<label/>").attr("for", fieldName).addClass("control-label").text(promptText);

    // Add text field
    var input = $("<input/>").attr("type", "text").addClass("form-control").addClass(valueType).attr("id", fieldName).attr("name", fieldName);

    // lbl and inp => form
    $(form).append(label).append(input);

    return $(form);
}
Mohawk answered 21/9, 2015 at 0:42 Comment(2)
Thanks it helped :)Raviv
is there a framework that does this in a formal/unified way ?Sputter
N
1

If it is just an empty div, this is sufficient:

$("#foo").append("<div>")

or

$("#foo").append("<div/>")

It gives the same result.

Nydianye answered 4/9, 2014 at 3:11 Comment(0)
E
1

$(HTMLelement) can success it. If you want an epmty div use it as $('<div></div>');. Also you can set the other elements by the same method. If you want to change inner HTML after created you can use html() method. For get outerHTML as string you can use is like this :

var element = $('<div/>');
var innerHTML = element.html(); // if you want set new HTML use it like this element.html('<b>new HTML</b>');
var outerHTML = element[0].outerHTML;
Edgar answered 25/3, 2016 at 11:14 Comment(0)
R
0

You can use .add() to create a new jQuery object and add to the targeted element. Use chaining then to proceed further.

For eg jQueryApi:

$( "div" ).css( "border", "2px solid red" )
  .add( "p" )
  .css( "background", "yellow" );
 div {
    width: 60px;
    height: 60px;
    margin: 10px;
    float: left;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
Rifling answered 25/9, 2015 at 11:20 Comment(1)
Sorry, this answer is not correct and should be deleted. OP was asking about creating a new DOM element. The jQuery add() method adds existing DOM elements to an existing jQuery object. The example you posted above (taken from the jQuery API page for add() ) adds a red border to the collection of 6 existing DIVs on the page, then adds the "p" element on the page to the collection and turns all 7 backgrounds yellow. It does not create any new DOM elements, as requested by the OP. I'm afraid I must -1 this answer. Recommend you delete it.Supercargo
T
-1

How about this? Here, pElement refers to the element you want this div inside (to be a child of! :).

$("pElement").append("<div></div");

You can easily add anything more to that div in the string - Attributes, Content, you name it. Do note, for attribute values, you need to use the right quotation marks.

Trombone answered 30/5, 2017 at 11:5 Comment(0)
H
-2

I've just made a small jQuery plugin for that.

It follows your syntax:

var myDiv = $.create("div");

DOM node ID can be specified as second parameter:

var secondItem = $.create("div","item2");

Is it serious? No. But this syntax is better than $("<div></div>"), and it's a very good value for that money.

(Answer partially copied from: jQuery document.createElement equivalent?)

Hammonds answered 16/8, 2013 at 8:6 Comment(4)
jQuery plugin just to create Divs, are you serious?Shimberg
As I mentioned, no.Hammonds
But this syntax is better than $("<div></div>"): you can just do $("<div>").Isolt
it's a very good value for that money.: jQuery is already free to use.Isolt

© 2022 - 2024 — McMap. All rights reserved.