Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 330
ilyo Avatar asked Jan 13 '13 07:01

ilyo


People also ask

Can Div have data attribute?

An <div> element can have any number of data-* attributes, each with their own name.

How add data attribute to div jQuery?

$('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 .

How do you add data attribute to HTML?

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.

How do you set the value of a data attribute?

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.


2 Answers

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.

like image 94
Brandon Kelly Avatar answered Oct 04 '22 22:10

Brandon Kelly


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/

like image 20
Joseph Silber Avatar answered Oct 04 '22 22:10

Joseph Silber