Search code examples
javascriptjqueryhtmlattr

jQuery attr() method to create a data dash attribute


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?


Solution

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