vorpyg
vorpyg

Reputation: 2525

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

When creating jQuery objects I've used the following syntax lately, as described here:

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

Safari 5.0.5 gives a syntax error at the point where I use the above construction.

Removing the second argument and adding classes with addClass removes the error, but seems rather unelegant.

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

Upvotes: 5

Views: 104

Answers (4)

Richard Dalton
Richard Dalton

Reputation: 35793

Make the attribute name a string:

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

JSFiddle Example

Upvotes: 3

Guffa
Guffa

Reputation: 700312

You get an error as class is a reserved keyword. You can use a string as identifier when a property name is a reserved keyword:

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

Upvotes: 1

SLaks
SLaks

Reputation: 887415

Since class is a reserved word, you need to put it in quotes.

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

Upvotes: 1

lonesomeday
lonesomeday

Reputation: 237845

You can't use class; it's a reserved word.

Use className instead:

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

Upvotes: 7

Related Questions