8

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";
pablo
  • 121
  • 2
  • 10
  • 1
    Pranav's answer below is correct. *Do not assume* that setting a property on a DOM Element object will also set the corresponding attribute. The top answer to this related question is a great overview on how this works in practice: https://stackoverflow.com/a/6004028/179125 – Jordan Running Jun 23 '17 at 16:46

2 Answers2

16

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

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • 1
    But you can also just say `s.dataset.flixDistributor`. By the way, what do you mean by "doesn't reflect in the HTML"? –  Jun 24 '17 at 06:20
  • 1
    @torazaburo : you are right - `any ASCII uppercase letter A to Z is transformed into a dash followed by its lowercase counterpart;` ---- – Pranav C Balan Jun 24 '17 at 06:25
  • @torazaburo : sorry it would reflect on the markup, thanks for correcting :) – Pranav C Balan Jun 24 '17 at 06:29
  • Note that the square bracket format with hyphens doesn't work anymore as it throws the following error: `Uncaught DOMException: An invalid or illegal string was specified` – Sv443 Jul 04 '23 at 12:27
2

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>