I'm trying to figure out why when adding a data-attribute to (Let's say an image) requires the attribute name to be put into quotes. I know that it needs to be done, but if a student asked me I wouldn't have the exact answer why. So take the two examples below.
1.) I'm looking for an explanation why the dash is a problem.
2.) Is there a way to escape it so you don't need to put it in quotes?
This Doesn't work:
$("img").attr({
alt: "a picture of my cat",
data-item : "pet",
data-color : "orange",
});
This Does work
$("img").attr({
alt: "a picture of my cat",
'data-item' : "pet",
'data-color' : "orange",
});
3.) The arguments that are passed to the attr() method is an object literal right?
4.) Is this just a rule in object literal syntax that a dash is not allowed?
The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element. When this method is used to set attribute values, it sets one or more attribute/value pairs for the set of matched elements.
To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API. $( "div" ).
$('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 .
The data-reactid attribute is a custom attribute that react can easily identify its components within the DOM. Just like the HTML “classes” and “id” attributes, “data-reactid” helps in uniquely identifying the element .
1.) In object literals, the -
symbol is not allowed as an identifier because it is also the minus operator in javascript.
2.) no, you have to use quotes.
3.) yes.
4.) yes, see 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With