ilyo
ilyo

Reputation: 36401

Create div with data attributes

I am creating div the following way

$('<div/>', {
    "class" : 'draggable player' + player + ' unit unit' + unit
})

And I can't find what other properties I can assign to it the same way I assign class. especially if I can assign data or attr?

Upvotes: 25

Views: 33223

Answers (2)

Brandon Kelly
Brandon Kelly

Reputation: 2163

According to the jQuery()function documentation (alias of $()), you can define attributes, events, and methods within that second parameter.

So yes, anything you’d define using attr() is fair game. That includes “data-whatever” attributes (which are oddly accessible via $elem.data('whatever')), however they will not be saved to jQuery.data like any variables defined via $elem.data('name', 'value') (at least until you call $elem.data('whatever') – see http://api.jquery.com/jQuery.data/#entry-longdesc-1).

So to clarify:

var $elem = jQuery('<div/>', { 'data-test': "Testing" });

will create this element, and return a jQuery object containing it:

<div data-test="Testing"></div>

From there, you will be able to do:

jQuery.data($elem[0], 'test'); // => undefined
$elem.data('test');            // => "Testing"
jQuery.data($elem[0], 'test'); // => "Testing"

Of course, $elem.attr('data-test') will also work.

Upvotes: 39

Joseph Silber
Joseph Silber

Reputation: 219936

You can assign any attributes you want:

$('<div/>', {
    "class" : 'draggable player' + player + ' unit unit' + unit,
    "data-info": 'Anything you want',
    "even-non-validating-attributes": 'ANYTHING!!'
});

Here's the fiddle: http://jsfiddle.net/vCaym/

Upvotes: 12

Related Questions