tags:

views:

36

answers:

4

Since version 1.4 of jQuery; you have been able to create an element using an object literal, defining the elements properties...

$("<div />",
{
    id: "test",
    name: "test",
    class: "test-class"
});

On top of assigning a few properties to an element; I'd like to add some in-line styles. Is this possible, using the object literal?... I'm thingking something along the lines of:

$("<div />",
{
    id: "test",
    name: "test",
    class: "test-class",
    style: {
        width: "100px",
        height: "100px",
        background-color: "#fff"
    }
});
+2  A: 

You can pass method names and arguments to the map that will be executed on the object.

$("<div />",
{
    id: "test",
    name: "test",
    class: "test-class",
    css: {
        width: "100px",
        height: "100px",
        backgroundColor: "#fff"
    }
});

From the documentation:

Furthermore, any event type can be passed in, and the following jQuery methods can be called: val, css, html, text, data, width, height, or offset.

Andy E
+1 for using something that's already built-in.
Tomas Lycken
A: 

You could always write your own helper method that would let you do

$('<div>',
{
    id: 'test',
    name: 'test',
    class: 'test-class',
    style: $.objectToCss(
    {
        width: '100px',
        height: '100px',
        background-color: '#fff'
    })
}

An entirely untested version of such a helper method might look something like this:

$.objectToCss = function(obj) {
    var css;
    $.each(obj, function(name, value) {
        css += name + ': ' + value + ';';
    });
    return css;
};
Tomas Lycken
+1  A: 

Instead of style use css, like this:

$("<div />", {
    id: "test",
    name: "test",
    "class": "test-class", //patrick's right, IE specifically doesn't like class
    css: {
        width: "100px",
        height: "100px",
        "background-color": "#fff"
    }
});

You can give it a try here, also note that background-color (since it has a dash) needs to be in quotes, or be backgroundColor. Other special properties are mapped this way, val, css, html, text, data, width, height and offset are treated special here.

Nick Craver
+1  A: 

Another solution (in a separate answer to make it possible to vote either of my solutions up or down separately) would be to just add a call to .css() afterwards:

$('<div>',
{
    id: 'test',
    name: 'test',
    class: 'test-class'
}).css(
{
    width: '100px',
    height: '100px',
    backgroundColor: '#fff'
});
Tomas Lycken