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">
version added: 1.0jQuery( "element" ) Refers to the tagName of DOM nodes.
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.
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.
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");
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');
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>');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With