andrew
andrew

Reputation: 9583

create element with data attribute using chaining

I wanted to create a new element and create a data attribute simultaneously by chaining using jQuery.data

So in the example here I want to create:

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

I tried:

$("<div>").data(this, 'test','test').append('test').appendTo('body');

Without success, is it possible?

here is a fiddle to play with

Upvotes: 2

Views: 519

Answers (3)

apsillers
apsillers

Reputation: 115950

The data-setting variant of .data takes only two arguments, a key and a value (and the data-getting variant only takes one argument). Remove your first argument to .data.

$("<div>").data('test','test').append('test').appendTo('body');

Note that jQuery's data doesn't set data- attributes; it stores values in an internal lookup table accessible with data-getting calls to .data. If you really need to set a data- attribute (e.g., for compatibility with other, non-jQuery code that expects one), you can set it explicitly with .attr:

$("<div>").attr('data-test','test').append('test').appendTo('body');

Note that the .data variant can store arbitrary values (because it uses an internal dictionary), while the .attr solution can only store strings (since it uses attribute values).

Upvotes: 2

Lix
Lix

Reputation: 47976

You can also set attributes (and content) for newly created elements in the same function call:

$( '<div>', { 
  'data-test': 'test',
  'text': 'test'
} ).appendTo( 'body' );

This code should yield something similar to this:

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

Upvotes: 5

Slippery Pete
Slippery Pete

Reputation: 3110

.data() only takes 2 arguments, key and value: http://api.jquery.com/data/

$("<div>").data('test','test').append('test').appendTo('body');

http://jsfiddle.net/yre9exte/2/

Upvotes: 0

Related Questions