Adding a css class to a html div that is only defined by the combination of css classes it uses with javascript

I have a website with a few sections that look as following:

...
    <div class="row docutils">
        ...
    </div>
...

I would like to use javascript to add a custom css class to them so they looks like this:

...
    <div class="row docutils my-class">
        ...
    </div>
...

I have tried adding a js file in the same directory and added a script reference, however this approach didn’t have any effect:

$(document).ready(function () {
   var testarray = document.getElementsByClassName("row docutils");
   for(var i = 0; i < testarray.length; i++)
   {
       testarray[i].className += "my-class";
   }
});

Is there a better way to solve this problem?

Answer

You have to prepend a space, since classes are delimited by a space.

var testarray = document.getElementsByClassName("row docutils");
for (var i = 0; i < testarray.length; i++) {
  testarray[i].className += " my-class";
}
.my-class {
  background-color: red;
}
<div class="row docutils">
  ...
</div>
<div class="row docutils">
  ...
</div>
<div class="row docutils">
  ...
</div>
<div class="row docutils">
  ...
</div>

Although you should be using classList.add instead:

var testarray = document.getElementsByClassName("row docutils");
for (var i = 0; i < testarray.length; i++) {
  testarray[i].classList.add("my-class");
}
.my-class {
  background-color: red;
}
<div class="row docutils">
  ...
</div>
<div class="row docutils">
  ...
</div>
<div class="row docutils">
  ...
</div>
<div class="row docutils">
  ...
</div>

If you want to do it with jQuery:

$('.row.docutils').addClass('my-class');
.my-class {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row docutils">
  ...
</div>
<div class="row docutils">
  ...
</div>
<div class="row docutils">
  ...
</div>
<div class="row docutils">
  ...
</div>