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

0

8 Answers 8

23

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");
2
  • 1
    Never knew the property thing, you can also add text, event handlers, even data, nice! Aug 27, 2012 at 13:52
  • This is the way to go if youre setting multiple properties. Much cleaner than passing in a long string.
    – pdizz
    Aug 27, 2012 at 15:46
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');
3
  • 1
    Thanks for answer but I have to create this element by using "div.someelement" ,
    – Matt
    Aug 27, 2012 at 13:41
  • 1
    Mm What about if "div.someelement" doesn't exist?
    – Matt
    Aug 27, 2012 at 13:53
  • @Matt: Why did you accept an answer that doesn't do what you asked in the question? Aug 27, 2012 at 14:30
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>');
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.

3
  • 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
    Aug 27, 2012 at 13:52
  • @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. Aug 27, 2012 at 13:53
  • @Matt: I added another answer that makes an element from a more complex string like you showed. Please see that answer. Aug 27, 2012 at 15:41
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");
1
  • 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
    – Matt
    Aug 27, 2012 at 13:44
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.

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.

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.