3

I have this elements in html:

<div id="element0div0">
div 0
</div>
<div id="element1div1">
div 1
</div>
<div id="element2div2">
div 2
</div>

can i use something like regex to apply css to element like element{n}div{n}?

1
  • ids and classes are created by cms. Commented Feb 11, 2013 at 18:16

2 Answers 2

4

There's no regular expression to differentiate between numbers and letters, but you can definitely approach a solution using:

div[id^=element][id*=div] {
    /* css */
}

This has flaws in that this will match the following (and more) id strings:

  • elementdiv
  • elementSomeOtherStringdiv
  • elementdivSomeOtherString

I'd suggest, given the nature of your question, that it'd be far wiser to simply use a common class-name to all the elements to which you wish to apply a common style.

References:

Sign up to request clarification or add additional context in comments.

2 Comments

is this possible that SomeOther be only integer?
No; CSS has, so far as I'm aware, no means to differentiate between letters, numerals or any other characters.
2

Yes you can but you must use JavaScript.

Using jQuery :

$('div').filter(function() {
   return this.id.match(/element[\d]+div[\d]+/)
}).css({color:'red'}); 

Using vanilla js :

for (var divs=document.getElementsByTagName('div'), i=0; i<divs.length; i++) {
    if (divs[i].id.match(/element[\d]+div[\d]+/)) divs[i].style.color="red";
}

This assumes you need to do what you asked, that is apply a style to elements found by a regex applied to their id. Most often you can find simpler solutions, though, like adding a class when building the HTML.

3 Comments

You realise there's no jquery, or javascript, tag? So while your answer would work, given the use of jQuery, you might want to explain that to the OP who, given the question, may not know how to implement your answer.
@DavidThomas you're right. I don't know why I thought this was a jQuery question. I updated.
No problem at all (seriously: I'm beginning to see those tags in my sleep!) =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.