2

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

2
  • 1
    I think you might be looking at $.data instead of .data Commented Sep 11, 2014 at 14:16
  • $('<div />', {'data-test' : 'test', text : 'test'}).appendTo('body') Commented Sep 11, 2014 at 14:22

3 Answers 3

5

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>
Sign up to request clarification or add additional context in comments.

3 Comments

append('test') is setting the innerhtml to "test"
+1 for using the constructor with properties (love that one).
@TrueBlueAussie - it is indeed very clean :)
2

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).

Comments

0

.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/

1 Comment

data will store values as behind-the-scenes-data and not a data- attribute on some browsers... Use attr.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.