Skip to main content

Regex Matching Attribute Selectors

By James Edwards

JavaScript

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

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:

#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…

James is a freelance web developer based in the UK, specialising in JavaScript application development and building accessible websites. With more than a decade's professional experience, he is a published author, a frequent blogger and speaker, and an outspoken advocate of standards-based development.

New books out now!

Learn the basics fo programming with the web's most popular language - JavaScript


A practical guide to leading radical innovation and growth.

Integromat Tower Ad