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 still cannot find and I am 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;">
Keep in mind that what you have is one
clase
and not oneid
to identify your element, it will return an array whengetElementsByClassName
using thefor
.With pure JavaScript (No Libraries or frameworks) through 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 string concatenation syntax += , (you should note that an extra space is needed otherwise the classes would end up together) .
If your element had an identifier it
(id)
would be directlyUsing Jquery , I would use addClass to add the name of a class to a given HTML element.
You can also add classes using the classList property , this property contains the following most important methods .
Add a class or more than 1 class
Delete a class or more than 1 class
Check if an element contains a class
For class handling of an element in javascript, I recommend using the object
classList
which provides methods to add, remove and check if an element is present in the list of classes.jquery-version
Version without jQuery
I recommend you always try to write code without jQuery.
I enclose a reference to
classList
so you can see more in detail its behavior.Fix for modern browsers.
It is possible to do the same as @Dev's answer. Joel, but using classList .
Unlike
className
, in this method you don't need to concatenate the existing classes with the one you want to add.It is used like this:
We also use querySelectorAll() , but you can still use it
getElementsByClassName
to get a list of nodes.CODE FRAGMENT:
jsFiddle
If you want to add more than one class using this method you have to separate each one by commas.
You can check the browsers that support this method here .
The property of the HTML objects that define the class, is
className
, is of type string .It can be modified directly, to add another class, simply add the text using
obj.className+=" nombre";
(Leave a space before it just like you would in HTML ).Example code: