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

Asked

Viewed 57 times

3

Friends I have several Divs on 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 is quite simple and useful.

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

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

Or I’m bound to make a loop for it?

2 answers

5


Use this:

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

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

  • rapaizzz , thank you so much for being so objective and answer Exactly my question! helped too!!!

  • 1

    Nothing, it’s a pleasure to help

  • Ahh yes .. detail, I forgot to thank the code for example working! for people who are not even know how to ask the question right, it is part essential !!!!!!!!!!!! It was worth once again!

3

Try adding a classe in common for all div’s you want to change, since you want to make exchange of classe in all at once, I do not think it recommended to select them by id since they all have this need in common. The use of the selector [id^="checker-"] solves the problem, however, it is a little heavier.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.