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?

4
  • $('<p>', {text: 'bla', 'data-test': 'some value'}).appendTo('#tagToAppendTo');?! Is that your issue? Commented Dec 1, 2017 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! Commented Dec 1, 2017 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 Commented Dec 1, 2017 at 10:30
  • Just FYI, JSON is a textual notation for data exchange. (More here.) 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.) Commented Dec 1, 2017 at 10:48

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Expanding your answer - if you use special chars as key of json, you have to use single or double quotes.
@Sylwek This has nothing to do with json, it is javascript object. JSON is just a notation and only double quotes is valid regarding JSON notation
@A.Wolff Yes, you're right. I wrote it in wrong words
@Sylwek I guess you get fooled by question's title :)
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>

Comments

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.