0

I want to set the data attribute for a tag (like data-id="..") using the following way:

$('<p>', {text: 'bla', data-?: '..'}).appendTo('#tagToAppendTo');

Unfortunetaly, I am not able to define the custom part (here marked as ?) in the object. Is there a way to do it like this, or do I need to resort to the .data() function?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Eti49
  • 140
  • 11
  • $('

    ', {text: 'bla', 'data-test': 'some value'}).appendTo('#tagToAppendTo');?! Is that your issue?

    – A. Wolff Dec 01 '17 at 10:28
  • I will try it again, i got an error doing it in this way. Update: I am dumb, i tried to set it without quotes. It makes sense that a custom attribute needs to be put in quotes. Thanks for the help! – Eti49 Dec 01 '17 at 10:29
  • But imho @Etibu, it is not really clear what you are asking here?! Especially because you are talking about `.data()` which isn't used for setting `data-*` attribute – A. Wolff Dec 01 '17 at 10:30
  • Just FYI, JSON is a *textual notation* for data exchange. [(More here.)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. *(Sorry, meant to post this earlier.)* – T.J. Crowder Dec 01 '17 at 10:48

2 Answers2

3

You can put the propety name in quotes when it's not a valid identifier name:

$('<p>', {text: 'bla', 'data-id': '..'}).appendTo('#tagToAppendTo');
// --------------------^-------^

Either single or double quotes are fine.

Is there a way to do it like this, or do I need to resort to the .data() function?

data doesn't set attributes. Details: jQuery .data() does not work, but .attr() does

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

You can make use of .attr option to set custom data-* values.

Snippet below.

$(document).ready(function(){
     $('<p>', {text: 'bla'}).attr('data-test','sample-value').appendTo('#tagToAppendTo');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tagToAppendTo"></div>
Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200