0

Is there a way to style an ID based on a specific word in the ID name?

If I have something like this:

<div id="name-of-id.1234">Something</div>
<div id="name-of-id.5678">Something</div>
<div id="name-of-id.4321">Something</div>

Normally I'd style it like this:

div#name-of-id\.1234,
div#name-of-id\.5678,
div#name-of-id\.4321 {
    color: #F0F;
}

But I'd MUCH RATHER do something like this:

div[# contains the word "name-of-id"] {
    color: #F0F;
}

Is there a way to target a specific word in an ID like that?

I have very limited access to the html - I can add scripts/styles to the layout, but that's about it.

Charles
  • 50,943
  • 13
  • 104
  • 142
gigglebot
  • 1
  • 1
  • see http://stackoverflow.com/questions/5110249/wildcard-in-css for info about wildcard selectors in CSS which is really what you're looking for here. – Zeph Jul 06 '12 at 18:08

2 Answers2

4

Use the CSS3 prefix substring matching attribute selector:

div[id^="name-of-id"] {
    color: #F0F;
}

It is supported by all current browsers. For support in older version of IE, use the Selectivizr polyfill. There is also a selector for suffixes ([id$="..."]) and for general substrings ([id*="..."]).

You
  • 22,800
  • 3
  • 51
  • 64
  • This is a pretty delayed response to this answer, but this css worked out great - just what I was looking for! – gigglebot Aug 13 '12 at 20:00
0

If you can add javascript (and you use jQuery), you could add something like this:

$('div').each(function(){
    if(this.id.match('name-of-id')) {
        $(this).addClass('someClass');
    }
});

Without jQuery, you could do:

var elems = document.getElementsByTagName('div');
for(var i=0; i<elems.length; i++) {
    if(this.id.match('name-of-id')) {
        this.className = this.className + 'someClass';
    }
}

And then style them with a class:

.someClass {
    /* your CSS styles */
}

Granted, running $('div') would be slow (as far as javascript is concerned) if your page contains a lot of them, so if you could narrow that selector down, this might be a more viable solution.

More to the point, there isn't a method I'm aware of to match partial ID names in CSS alone.

jackwanders
  • 15,612
  • 3
  • 40
  • 40