pablo
pablo

Reputation: 123

How to add an attribute with a hyphen in the name to a script element?

I want to do something like this but I get an "Invalid left-hand side in assignment" error.

var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://example.com/example.js";
s.data-flix-distributor = "12994";

Upvotes: 9

Views: 9949

Answers (2)

user663031
user663031

Reputation:

The preferred way to set a data- attribute is via element.dataset. As with styles, there will be automatic conversion from dasherized to camelCase format and vice versa. So

s.dataset.flixDistributor = "12994";

yields:

<div data-flix-distributor="12994"></div>

Upvotes: 2

Pranav C Balan
Pranav C Balan

Reputation: 115222

In case you want to set a property using dot notation then it should be valid identifier other case use bracket notation.

Refer : custom attribute works only with element.getAttribute("attribute") but not "element.attribute"


To set an attribute to the element use setAttribute() method.

s.setAttribute('data-flix-distributor', "12994");

Or update in dataset property.

s.dataset['flix-distributor'] = "12994";

// or you can use camelCase to dash-style to use dot notation
s.dataset.flixDistributor = "12994";

Refer : Name conversion in dataset property

Upvotes: 17

Related Questions