How to add a class to a div using JavaScript?

Question:

I need to add the following bootstrap attribute (col-md-6) to a div which by default is already printed with an existing class:

<div class="images" style="opacity: 1;">

You will say to do it directly but it is a PHP template that I can not find yet and I have tired of looking for it in the package. Therefore I intend it to be as follows by means of a JavaScript sequence.

<div class="col-md-6 images" style="opacity: 1;">

Answer:

Keep in mind that what you have is a clase and not an id to identify your element, it will return an array when doing getElementsByClassName therefore the use of the for .

  • With pure JavaScript (No Libraries or frameworks) using className this property will return a string with the classes of the selected element, to add a certain class to an element you can add the name of the class for this you could use the basic syntax of string concatenation + = , (you should note that an additional space is needed otherwise the classes would end together) .

     var elemento = document.getElementsByClassName("images"); for(var i = 0; i < elemento.length; i++) elemento[i].className += " col-md-6";

If your element had an identifier (id) would be directly

    var elemento = document.getElementById("images");
    elemento.className += " col-md-6";
  • Through Jquery, I would use addClass to add the name of a class to a certain element of the HTML

     $('.images').addClass('col-md-6');
  • You can also add classes using theclassList property, this property contains the following most important methods.

    1. Add a class or more than 1 class

       myElemento.classList.add('nombreclase'); myElemento.classList.add('nombreclase1','nombreclase2');
    2. Delete a class or more than 1 class

       myElemento.classList.remove('nombreclase'); myElemento.classList.remove('nombreclase1','nombreclase2');
    3. Check if an element contains a class

       myElemento.classList.contains('nombreclase');
Scroll to Top