开发者

what is more efficient applying class or id to a element in dom?

If we have just one element on which we have to apply css or javascript. What is more efficient giving it a class or id?. I understand that ideally we should be giving id but i have a scenario where i have an already written code and 开发者_如何转开发i want to change it only if there is a performance involved.


This depends completely on the browser's DOM implementation. In theory, using id might be a little better performancewise, but too little to matter in most cases. In practice, the browser may implement it arbitrarily inefficient.

If performance is crucial to you, benchmark. It's unlikely to make an difference on any browser more modern than IE6.


in theory, the id-selector should be faster as the id should be unique in a document. practical, almost every browser allows to use an id multiple times without breaking wich doesn't make this have any effect - so if there even is a difference in performane, the id-selector is faster, but the difference will be so tiny you won't ever notice it.


check this blog post : http://www.stevesouders.com/blog/2009/06/18/simplifying-css-selectors/

Basically if your class is applied only on a few elements from the page, there will be no performance differences between id selector and class selector.


The ID is always the more efficient and fastest way for both CSS engine and JavaScript DOM manipulation.

You can try the speed yourself with JavaScript by timing the same amount of operations by using id or classes.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜