🤯 50% Off! 700+ courses, assessments, and books

Regex Matching Attribute Selectors

    James Edwards

    They don’t exist, but wouldn’t that be so cool? I’ve no idea how hard it would be to implement the regex, or how to expensive to parse, but wouldn’t it just be the bomb?

    Let’s say I have a bunch of elements, all with similar class names, which have some shared styling but also need individual rules, for example:

    <ul id="menu">
    	<li id="menu-home"><a href="/">Home</a></li>
    	<li id="menu-products"><a href="/products/">Products</a></li>
    	<li id="menu-about"><a href="/about/">About</a></li>

    I could do image replacement on those list-items to create a graphical navigation bar, with rules like this:

    #menu li
    	background:none #fff no-repeat;
    #menu li#menu-home
    #menu li#menu-products
    #menu li#menu-about

    Not too bad, but as the structure grows in size, so the CSS grows too. If the structure got very large so the CSS would become equally verbose; not to mention the fact that I have to manually edit it each time a new item is added.

    But what if I could just do this:

    #menu li[id%="/^menu-([a-z]+)$/"]

    Now my menu styles are infinitely extensible — I can add any number of new items, without ever having to touch the CSS!

    Just a thought…