How to use hyphen in object name?

$('.class').data({data-toggle: "whatever-value", data-target: "#id"});

I keep getting syntax errors for -

I initially tried .attr and then switched to .data because I thought it would fix it.

Can someone help with this easy problem?

thanks

+6
source share
2 answers

If you want to set / update the data-* attribute, you will need quotes if you set the attribute:

 $('.class').attr({"data-toggle": "whatever-value", "data-target": "#id"}); 

Otherwise, he analyzes it as

 data-toggle 

value

 data - toggle 

subtracting two variables.

You can also use .data() with

 $('.class').data({"toggle": "whatever-value", "target": "#id"}); 

but does not assign data-* attributes, it just saves the data in jQuery storage system.

+6
source

To add to what alredy pointed out, in Javascript, objects have properties defined by arbitrary strings.

obj.prop is really just sugar for obj["prop"] , the latter being more expressive because all characters are allowed in the latter. Similarly, {prop: "val"} really sugar for {"prop": "val"} . This is just one of many times when you have to resort to desugared syntax.

+4
source

All Articles