Best Practice for Naming the Id Attribute of Dom Elements

前端 未结 5 1462
半阙折子戏
半阙折子戏 2021-02-04 03:14

This is related to naming conventions for a DOM element\'s id attribute and I guess the name attribute as well. When it comes to JavaScript, from what I understand and have done

5条回答
  •  时光说笑
    2021-02-04 03:38

    • Keep it semantic. Use complete, simple, (preferably English) words. Don't try to come up with something fancy or technical, and don't describe what it is - we know that. Describe what it does. Describing purpose adds informational value.

    • Don't abbreviate anything! BW_RCB01_SW meant something to the team who did our CSS to years ago, but it doesn't mean anything to me now and I have to work backwards to try to translate what BW_RCB01_SW corresponds to for my purposes, and either remember that translation or document it somewhere. Better? blackwhite-boxtype1-bottomleft. It's longer but also doesn't require a Rosetta stone.

    • Keep it all lower-case and use underscores or hyphens. I prefer hyphens, but that's totally a preference. There should be no impediment to using hyphens, since they are not reserved in CSS or HTML and IDs are treated as literal strings in every other language. Lower case is all experience - too many hours wasted wondering why the heck won't this style apply oh. pageContainerLeft is not the same as pageContainerleft.

    • Identify exactly what that element is, but no more. Think seriously about each piece of information you're embedding in the name and whether it's necessary. In your example - do you need to know it's a checkbox by the ID? Unlikely. You already know what element you're referring to because it's a unique ID and you have to code against that element anyway.

提交回复
热议问题