Creating a div element in jQuery

Posted in :

想在 jsplumb 裡動態新增視窗, 原來只需要新建一個 div node, 指定 classname 與 id 後, append 進去 parent node 就可以了.

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.

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

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.

d = document.createElement('div');
$(d).addClass(classname)
    .html(text)
    .appendTo($("#myDiv"))
.click(function () {
    $(this).remove();
})
);

Example 2:
https://stackoverflow.com/questions/867916/creating-a-div-element-in-jquery


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.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *