Create Element in Jquery

Matt picture Matt · Aug 27, 2012 · Viewed 37.3k times · Source

I would like to create element in Jquery/Javascript by using "div.someelement" like this

var SomeElement = $("div.someelement");
$( "#container" ).append( SomeElement );

But I don't want to copy element with the same class, I would like to create new one.

document.createElement is creating "<div.somelement>" instead of <div class="someelement">

Answer

Jishnu A P picture Jishnu A P · Aug 27, 2012

I would use the following method to create elements on the fly

$("<div/>",{
    "class" : "someelement",
    // .. you can go on and add properties
    "css" : {
        "color" : "red"
    },
    "click" : function(){
        alert("you just clicked me!!");
    },
    "data" : {
       "foo" : "bar"
    }
}).appendTo("#container");