What is the preferred way to create a jQuery object with attributes?

When creating jQuery objects, I used the following syntax recently, as described here :

var $el = $('<div/>', {
   class: 'class-1 class-2'
});

Safari 5.0.5 gives a syntax error at the point where I am using the above construct.

Removing the second argument and adding classes with addClass fixes the error, but seems rather inelegant.

How do you create your objects? I tried using attr ({class: 'class-1'}), but got the same syntax error.

+5
source share
4 answers

You cannot use class; it is a reserved word.

className:

var $el = $('<div/>', {
   className: 'class-1 class-2'
});
+7

:

var $el = $('<div/>', {
    'class': 'class-1 class-2'
});

JSFiddle

+3

Since it classis a reserved word, you need to put it in quotation marks.

var $el = $('<div/>', {
   "class": 'class-1 class-2'
});
+1
source

You will receive an error message because it classis a reserved keyword. You can use the string as an identifier if the property name is a reserved keyword:

var $el = $('<div/>', {
   'class': 'class-1 class-2'
});
+1
source

All Articles