Is it possible to change class of many DIVs with a single js command?

3

Friends I have several DIVs in my page, each with its ID, but with the same pattern, for example "checker-001", "checker-002", and so on ... where, I use a JS to change its characteristics, for example

$('#checker-363').removeClass('UmaVelhaClass').addClass('UmaNovaClass');

That's quite simple and useful.

Here's my question : Is it possible to exchange hundreds of DIVs at a time? with a single command? for example changing the "number" by a "*":

 $('#checker-*').removeClass('UmaVelhaClasse').addClass('UmaNovaClasse');

Or am I forced to loop through this?

    
asked by anonymous 22.03.2016 / 09:42

2 answers

5

Use this:

$('[id^="checker-"]').removeClass('UmaVelhaClasse').addClass('UmaNovaClasse');

When you use the [id^="checker-"] selector you are looking for all elements that have the id that start with that pattern, in the checker- case.

    
22.03.2016 / 10:32
3

Try adding a common classe to all the div's that you want to change, since you want to change classe all at once, I do not think it's recommended to select them with id since all have this need in common. Using the [id^="checker-"] selector resolves the problem, however, it is a bit heavier.

An example of usage would be: $('.classeEmComum').removeClass('UmaVelhaClasse').addClass('UmaNovaClasse');

    
22.03.2016 / 13:19