JavaScript
Article
By James Edwards

Regex Matching Attribute Selectors

By James Edwards

They don’t exist, but wouldn’t that be so cool? I’ve no idea how hard it would be to implement, 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>
</ul>

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

--ADVERTISEMENT--

#menu li
{
	background:none #fff no-repeat;
}

#menu li#menu-home
{
	background-image:url("home.png");
}

#menu li#menu-products
{
	background-image:url("products.png");
}

#menu li#menu-about
{
	background-image:url("about.png");
}

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]+)$/"]
{
	background-image:url("$1.png");
}

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…

Recommended
Sponsors
The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account