Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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";
like image 820
pablo Avatar asked Jun 23 '17 16:06

pablo


People also ask

Can you use hyphen in JavaScript?

Hyphens are not allowed in JavaScript names.

Where are attributes added in an element?

Attributes define additional characteristics or properties of the element such as width and height of an image. Attributes are always specified in the start tag (or opening tag) and usually consists of name/value pairs like name="value" .


1 Answers

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

like image 67
Pranav C Balan Avatar answered Sep 22 '22 22:09

Pranav C Balan