Is there a CSS selector by class prefix? -
i want apply css rule element 1 of classes matches specified prefix.
e.g. want rule apply div has class starts status-
(a , c, not b in following snippet):
<div id='a' class='foo-class status-important bar-class'></div> <div id='b' class='foo-class bar-class'></div> <div id='c' class='foo-class status-low-priority bar-class'></div>
some sort of combination of:
div[class|=status]
, div[class~=status-]
is doable under css 2.1? doable under css spec?
note: know can use jquery emulate that.
it's not doable css2.1, possible css3 attribute substring-matching selectors (which are supported in ie7+):
div[class^="status-"], div[class*=" status-"]
notice space character in second attribute selector. picks div
elements class
attribute meets either of these conditions:
[class^="status-"]
— starts "status-" (obviously).[class*=" status-"]
— contains substring "status-" occurring directly after space character. class names separated whitespace per html spec, hence significant space character. checks other classes after first if multiple classes specified, and adds bonus of checking first class in case attribute value space-padded (which can happen applications outputclass
attributes dynamically).
naturally, works in jquery, demonstrated here.
the reason need combine 2 attribute selectors described above because attribute selector such [class*="status-"]
match following element, may undesirable:
<div id='d' class='foo-class foo-status-bar bar-class'></div>
if can ensure such scenario never happen, free use such selector sake of simplicity. however, combination above more robust.
if have control on html source or application generating markup, may simpler make status-
prefix own status
class instead as gumbo suggests.
Comments
Post a Comment