Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 586
Eric Bishard Avatar asked Jul 25 '14 07:07

Eric Bishard


People also ask

What is the use of attr () method in jQuery?

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.

How get data attribute in jQuery?

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

How add data attribute in HTML using jQuery?

$('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 .

What is data ID attribute?

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 Answers

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.

like image 121
Ferdi265 Avatar answered Sep 22 '22 01:09

Ferdi265