开发者

Distinguish between CSS classes for style and Javascript

I often use CSS ids or classes to select elements in Javascript. Many of those classes do just exist for that use case and do not have any styles attached at all.

I ponder now if it would be any good to mark t开发者_StackOverflowhose classes explicitly. Maybe something like a leading underscore (e.g. class="_field").

The thing is that I never heard of such a practice. Is this recommended? Maybe already used in a bigger project? What kind of marking would make sense? I read somewhere that a leading underscore could be problematic. What else could I use to easily identify those "Javascript only" classes?


You can do that as a personal coding convention. The spec doesn't state that the class attribute must be used in styling only, or in scripting only. You can use it to classify your elements in any way you want, so there's no restriction in how you name and organize your classes.


The majority of the time I find that the class names used in JS matches the styling I want to do in CSS. As long as you name them properly it's not a big deal that a class name is used by only CSS or JS.


You may want to use the data-* attributes suggested by HTML5. They even work in HTML4, though the resulting code is not valid.

As a sidenote, ExtJS has used "namespaced" custom attributes for their tree nodes for quite some time:

<div class="x-tree-node-el x-tree-node-leaf x-unselectable cls"
     ext:tree-node-id="Foobar">

(They should change that to data-ext-tree-node-id btw)


It is better to use ids for working with JavaScript since an element has only one id that is unique to it, while classes can be applied to multiple HTML elements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜