-2

I followed all the answers on this post jQuery: Adding two attributes via the .attr(); method and none of them work for multiple attributes, only single attribute work.

E.g.

$("img").attr({
data-aos: "fade-down",
data-aos-duration: "600"
});

Does not work. But single attribute does work:

$("img").attr("data-aos", "fade-down");

https://jsfiddle.net/bwj5uex0/3/ You can test on JSFiddle with your browser's built-in dev tools after CTRL+Enter.

5
  • As you can see from the syntax highlighting in the Fiddle, the - character is being interpreted as the subtraction operator, so you have a syntax error. You instead need to wrap the attribute names in quotes: jsfiddle.net/bwj5uex0/4. Voting to close as a typo Commented Jun 21, 2018 at 15:40
  • 2
    Did you read beyond the accepted answer? You said "all" answers, yet there it is: $(myObj).attr({"data-test-1": num1, "data-test-2": num2}); Commented Jun 21, 2018 at 15:43
  • @freedomn-m it's not working, because num1 num2 not quoted as answered below in this question. Commented Jun 21, 2018 at 15:44
  • @freedomn-m Apparently this solution works if it's all in one line, if you break into new lines values and attributes both must be in quotes. Commented Jun 21, 2018 at 15:51
  • "values and attributes must be in quotes" - not if you're using a variable, but yes if it's a string. Newlines / spaces have no impact (other than in a rare case which doesn't count here). Commented Jun 22, 2018 at 7:43

2 Answers 2

7

Just quote the names:

$("img").attr({
    "data-aos": "fade-down",
    "data-aos-duration": "600"
});

This is a standard feature of JavaScript object initializers, and works with jQuery's attr. The property names can be literals (foo:), string literals ("foo": or 'foo':), numeric literals (1:) (they get converted to string), or (in ES2015 onward) computed names using [] notation.

Live Example (right-click the image and choose Inspect / Inspect Element to see the attributes):

$("img").attr({
    "data-aos": "fade-down",
    "data-aos-duration": "600"
});
<img src="http://via.placeholder.com/200/44F/DDD?text=hi+there">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

You may get people suggesting you use data for this instead of attr. Many people have a misunderstanding, thinking data is an accessor for data-* attributes. It isn't; details here.

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

Comments

-2

Alternatively, you can use the camelCase style for keys declaration

$("img").attr({
    dataAos:"fade-down",
    dataAosDuration:"600"
})

1 Comment

Not for custom data-* properties. The above will put dataaos="fade-down" on the element, not data-aos="fade-down".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.