Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Element in Jquery

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">

like image 976
Matt Avatar asked Aug 27 '12 13:08

Matt


People also ask

What is an element in jQuery?

version added: 1.0jQuery( "element" ) Refers to the tagName of DOM nodes.

What does $() mean in jQuery?

In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery. A (selector) to "query (or find)" HTML elements.

How HTML element is used in jQuery?

jQuery html() MethodThe html() method sets or returns the content (innerHTML) of the selected elements. When this method is used to return content, it returns the content of the FIRST matched element. When this method is used to set content, it overwrites the content of ALL matched elements.


3 Answers

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");
like image 98
Jishnu A P Avatar answered Oct 23 '22 07:10

Jishnu A P


Try this:

var $someelement = $('<div class="someelement"/>').appendTo('#container');

This will create a brand new element inside of #container and save it as $someelement for easy reference later.

http://api.jquery.com/jQuery/#jQuery2

UPDATE

You could clone the original then empty it out. This doesn't affect the original element at all.

var $someelement = $('div.someelement').clone().empty().appendTo('#container');
like image 35
iambriansreed Avatar answered Oct 23 '22 08:10

iambriansreed


You can do this by the following:

var newElement = $('<div class="someelement"></div>');
$('#container').append(newElement);

or if you don't need the element you can directly append it:

$('#container').append('<div class="someelement"></div>');
like image 3
Fidi Avatar answered Oct 23 '22 07:10

Fidi