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

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Adding a css class to a html div that is only defined by the combination of css classes it uses with javascript without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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>
We are here to answer your question about Adding a css class to a html div that is only defined by the combination of css classes it uses with javascript - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji