Dan Rubio Dan Rubio - 1 month ago 5
CSS Question

How can I remove a dynamically generated class with jQuery?

I am creating a dynamically generated html grid with the following javascript code and html:

1 <!DOCTYPE html>
2 <html>
3 <head>
4 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
5 <link rel="stylesheet" href="./css/colorwalk.css">
6 </head>
7 <body>
8 <div>
9 <div id="colorgrid"></div>
10 </div>
11 <div id="colorbuttons">
12 <button class="buttonsize white">
13 <button class="buttonsize red">
14 <button class="buttonsize green">
15 <button class="buttonsize orange">
16 <button class="buttonsize pink">
17 <button class="buttonsize purple">
18 </div>
19 <script src="js/main.js"></script>
20 </body>



1 $(document).ready(function() {
2 const colors = Array.of('red','green','orange','pink','purple');
3 let y = 0;
4 let x = 0
5 for (i = 0; i < 20; i++) {
6 for (j = 0; j < 30; j++) {
7 const randomColor = colors[Math.floor(Math.random() * colors.length)];
8 $block = $("<div></div>").addClass("blockattribute").addClass(randomColor).css({left: x, top:y});
9 $block.appendTo("#colorgrid");
10 x >= 580 ? x = 0 : x = x + 20
11 $('.blockattribute').first().addClass('gray');
12 }
13 y = y + 20;
14 }
15 });


The problem that I am encountering is line 11. I want the very first block on the grid to have a class of
.gray
. The class makes the background color gray but when I inspect the element in the console I see that my block looks like this:

<div class="blockattribute red gray" style="left: 0px; top: 0px;"></div>


My problem is that I need to remove the
red
class but because it is dynamically created, I am unable to select it before hand. Is there a way I can see a list of jQuery classes and then select the right one?

Answer

You can remove all other color classes before adding gray like follwing

$('.blockattribute').first().removeClass(colors.join(' ')).addClass('gray');