Javascript and CSS, using dashes

2019-01-14 03:49发布

I'm starting to learn some javascript and understand that dashes are not permitted when naming identifiers. However, in CSS it's common to use a dash for IDs and classes.

Does using a dash in CSS interfere with javascript interaction somehow? For instance if I were to use getElementByID("css-dash-name"). I've tried a few examples using getElementByID with dashes as a name for a div ID and it worked, but I'm not sure if that's the case in all other context.

7条回答
不美不萌又怎样
2楼-- · 2019-01-14 04:26

IDs are allowed to contain hyphens:

  • ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

And there is no restriction when using IDs in JavaScript except if you want to refer to elements in the global scope. There you need to use:

window['css-dash-name']
查看更多
登录 后发表回答