最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to add an attribute with a hyphen in the name to a script element? - Stack Overflow

programmeradmin3浏览0评论

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 = ".js";
s.data-flix-distributor = "12994";

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";
Share Improve this question asked Jun 23, 2017 at 16:36 pablopablo 1233 silver badges11 bronze badges 1
  • 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: stackoverflow.com/a/6004028/179125 – Jordan Running Commented Jun 23, 2017 at 16:46
Add a comment  | 

2 Answers 2

Reset to default 17

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

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>
发布评论

评论列表(0)

  1. 暂无评论