[css-dom] .classList

In using CSS/DOM to manipulate pages via Javascript, I regularly run into a complication with classes. Adding and removing classes is not a straight-forward task. For example, starting with a tag like:

<div class="dice diced"/>

Asking the question "Is the .dice class applied?" is easy to screw-up. An unsuspecting programmer would approach the problem as so:

var div = // get the div
if( ( new String( div.className ) ).indexOf( "dice" ) )

The script checks for the existence of the string "dice". Unfortunately, if the class simply contained the class "diced" and no other, the above check would return true and a bug would result. Ultimately, such a check demands Regular Expressions.

Adding classes is also slightly non-trivial, as you must check if you need to append a space, and if you need to guarantee order of certain classes, a RegExp is again required.

All of this work is entirely unnecessary considering the User Agent will inevitably implement the classlist internally as a HashTable, or a dynamic array of CssClass objects, and not a kludgy tokenized string. Further, all of the RegExps involved damage the performance of client-side scripts, which goes against one of the intents of CSS.

So, why not add a further CSS-DOM property to the Element class? It could be named .classList, and could include a length property, a .item indexer, and perhaps even .has( sClassName ) and .insert( sClassName, iIndex ) methods.

-Chris "SoopahMan" Moschini
http://hiveminds.info/
http://soopahman.com/

Received on Tuesday, 23 December 2003 11:23:43 UTC