15

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

Barlas Apaydin
7,35511 gold badges60 silver badges88 bronze badges
asked Aug 27, 2012 at 13:37
0

8 Answers 8

22

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");
answered Aug 27, 2012 at 13:44

2 Comments

Never knew the property thing, you can also add text, event handlers, even data, nice!
This is the way to go if youre setting multiple properties. Much cleaner than passing in a long string.
20

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');
answered Aug 27, 2012 at 13:39

3 Comments

Thanks for answer but I have to create this element by using "div.someelement" ,
Mm What about if "div.someelement" doesn't exist?
@Matt: Why did you accept an answer that doesn't do what you asked in the question?
3

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>');
answered Aug 27, 2012 at 13:40

Comments

1

According to the question you want to use a syntax like "div.someelement" to create an element.

In order to do that, you need to make your own parser.

It is very simple if that will be the exact syntax.

var str = "div.someelement",
 parts = str.split("."),
 elem = $("<" + parts.shift() + ">"),
 cls;
while (cls = parts.shift())
 elem.addClass(cls);

But if you're going to do this, you might as well use native methods.

var str = "div.someelement",
 parts = str.split("."),
 elem = document.createElement(parts.shift());
elem.className = parts.join(" ");

If you want to allow for full CSS syntax for creating an element, then you may want to look at the regex parser that Sizzle uses, and use it for your needs.

answered Aug 27, 2012 at 13:47

3 Comments

Hello, Your option is better. But there isn't any other way to do that? Cause in the option could be "div[href=somehref" instead of "div.someelement".
@Matt: If you want any valid CSS syntax, then you'll need a CSS string parser. The SizzleJS project has one built in that you could borrow. You'll need to modify code to your needs.
@Matt: I added another answer that makes an element from a more complex string like you showed. Please see that answer.
1

Use this:

var someElement = $("<div></div>");
someElement.addClass("someelement");
$("#container").append(someElement);

Or you can chain together the calls:

$("#container").append(
 $("<div></div>")
 .addClass("someelement")
);

EDIT:

Perhaps I misunderstood the question, maybe this will help. To create a new set of elements, use jQuery's clone method:

$("div.someelement").clone().appendTo("#container");
answered Aug 27, 2012 at 13:39

1 Comment

Thanks for answer but it isn't what I need. I know that there is that possibility, but it doesn't satisfied me. I have option in Jquery Plugin like someContainer: "div.someelement", and I have to create this element by someContainer Option
1

I would use zen coding for textarea as a starting point. Its syntax is close enough for what you are trying to do, its a well understood implementation. You should be able to invoke the transformation from a raw string rather than from a textarea with a little tweaking.

answered Aug 27, 2012 at 13:59

Comments

0

Since you are asking about creating an element from css syntax, you need to use a parser to interpret the syntax.

Here is an example you can build from. This will match an element name followed by id, class or other attributes. It won't cover some edge cases, but will work in most cases.

var elem_regex = /^(\w+)?|(#|\.)([^.#\[]+)|(\[[^\]]+?\])/g

Then make a function to get the parts and create an element.

function elementFromSelector(str) {
 var match, parts = {}, quote_re = /^("|').+(1円)$/;
 while (match = elem_regex.exec(str)) {
 if (match[1]) 
 parts.name = match[1];
 else if (match[2] === ".") {
 if (!parts.clss) 
 parts.clss = [];
 parts.clss.push(match[3]);
 } else if (match[2] === "#")
 parts.id = match[3];
 else if (match[4]) {
 var attr_parts = match[4].slice(1,-1).split("="),
 val = attr_parts.slice(1).join("");
 parts[attr_parts[0]] = quote_re.test(val) ? val.slice(1,-1) : val;
 }
 else throw "Unknown match";
 }
 if (parts.name) {
 var elem = document.createElement(parts.name);
 delete parts.name;
 for (var p in parts)
 if (p === "clss")
 elem.className = parts[p].join(" ");
 else
 elem[p] = parts[p];
 return elem;
 } else throw "No element name at beginning of string";
}

Then pass a proper string to the function, and it will return the element.

var str = 'input#the_id.firstClass.secondClass[type="text"][value="aValue"]';
var element = elementFromSelector(str);

Before creating the element, the parts look like this.

{
 "name": "input",
 "id": "the_id",
 "clss": [
 "firstClass",
 "secondClass"
 ],
 "type": "text",
 "value": "aValue"
}

Then it uses that info to create the element that gets returned.

answered Aug 27, 2012 at 15:11

Comments

0

Simply create a new Element for jQuery:

var $newElement = $(document.createElement("div"));
$newElement.appendTo($("body"));

if you want to at attributes to de element simplie use:

$newElement.attr({
 id : "someId",
 "class" : "someClass"
});

Rember by class always use like this "class", because class is a reserved name

bummi
27.4k14 gold badges66 silver badges105 bronze badges
answered Sep 11, 2013 at 14:11

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.