For example, there are elements with identifiers:

index1 index2 index3 

I want to change the background all at once. I imagine it like this:

 var reg = new RegExp("\d"); document.getElementById('index' + reg).style.background='#000'; 

Explain, please, how to do it right? :)

upd: The number of items is unknown. Is it possible to do without jQuery?

  • one
    You can make a wrapper function, such as here: But this is very low-performing. Although it is possible to create in advance a cache of all items with an ID and make a selection from the cache, this will be a little faster. - ReinRaus

2 answers 2

If it is known that the elements n:

 index1 index2 index3 indexn 


 var n = 5; // 5 элементов for (var i = 1; i <= n; i++){ document.getElementById('index' + i).style.background='#000'; } 
  • @Rules be careful, you will work out 4 elements, because less than five condition. Here you need the sign "less or equal" (<=). - lampa
  • Thanks, @lampa - fixed! - Rules

On jQuery:

 $('#index1, #index2, #index3').css("background-color","red"); 

Pure CSS:

 #index1, #index2, #index3 { background-color: red; } 

Ordinary getElementById does not accept regular expressions, so without jQuery you will need 3 queries.

If the number of elements is unknown, it’s better to go straight, give them a general class and use pure CSS:

 .yourclass { background-color: red; } 

Or (less correctly) without a class with CSS3:

 [id^="index"] { background-color: red; } 

Or use the @Spectre advice.

  • 2
    and if there is an unknown number of elements, then: $ ('[id * = "index"]') - [Attribute Contains Selector [name * = "value"]] ( ) - Specter
  • one
    @Spectre: ... but then the best solution would probably be a general class. - VladD
  • surely - Specter