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
?
An <div> element can have any number of data-* attributes, each with their own name.
$('div'). attr('data-info', 1); $('div')[0]. setAttribute('data-info',1); In order to access an element with the attribute set, you can simply select based on that attribute as you note in your post ( $('div[data-info="1"]') ), but when you use .
Adding a data attribute is easy. Any HTML element can have any number of data attributes added to its opening tag. We simply type data- followed by the name of our attribute into the element's opening tag alongside any other attributes we're already using.
To set an attribute and value by using a function using this below syntax. $(selector). attr(attribute,function(index,currentvalue)) ; To set multiple attributes and values using this below syntax.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With