For instance, if you need to select an element with the class ID Students, here’s how to select it.
After selecting the element using its class ID, you can change its class or replace all its classes, as shown above. You will need to set a new one using the
.className attribute to replace the old class, as shown below.
Document.getElementById("Fruits").classname = "Veggies";
You can also add a new class to an element without changing any of the existing classes. You can do this by using the += operator, a singular space, and adding the new class.
Document.getElementById("Subjects").className += "Physics";
It adds an extra class named Physics to other classes in the Subjects element.
Deleting a single class in an element without affecting other classes is slightly more complex. You will need to use the
.className.replace together with the following regex.
?:^|\scaptures the beginning of a string and/or any single whitespace character used.
RemoveThisis the name of the class to be removed.
RemoveThisis a full class name and checks for any non-space characters at the end. In other words, it ensures that the regex is placed at the end of the string.
gis the flag that ensures that the replace command is effected as necessary in all cases where the class has been added.
It would therefore be written (in an example) as follows.
document.getElementById("ElementOne").className = document.getElementById("ElementOne").className.replace( /(?:^|\s)RemoveThis(?!\S)/g , '' )
To check whether a class has been applied to a specific element, you can use the regex above . This Is best achieved using an
if(); statement to give a result. For instance:
if ( document.getElementById("ElementOne").className.match(/(?:^|\s)ClassOne(?!\S)/) ) print ("Class has been used.")
The output will be
Class has been used if the check comes out positive, or no output if it is negative unless an alternative action or output is defined with the