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

user3108268
  • 1,043
  • 3
  • 18
  • 37
  • 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: https://jsfiddle.net/bwj5uex0/4/. Voting to close as a typo – Rory McCrossan Jun 21 '18 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});` – freedomn-m Jun 21 '18 at 15:43
  • @freedomn-m it's not working, because `num1 num2` not quoted as answered below in this question. – user3108268 Jun 21 '18 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. – user3108268 Jun 21 '18 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). – freedomn-m Jun 22 '18 at 07:43

2 Answers2

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
-2

Alternatively, you can use the camelCase style for keys declaration

$("img").attr({
    dataAos:"fade-down",
    dataAosDuration:"600"
})
MadPapo
  • 495
  • 4
  • 13
  • 1
    Not for custom `data-*` properties. The above will put `dataaos="fade-down"` on the element, not `data-aos="fade-down"`. – T.J. Crowder Jun 21 '18 at 15:49