Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply css to elements with same pattern

Tags:

html

regex

css

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}?

like image 258
user1903750 Avatar asked Sep 16 '26 22:09

user1903750


2 Answers

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:

  • CSS attribute-selectors.
like image 185
David Thomas Avatar answered Sep 18 '26 12:09

David Thomas


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.

like image 37
Denys Séguret Avatar answered Sep 18 '26 12:09

Denys Séguret