Skip to content
Advertisement

Toggle between classes using JavaScript

I have following code.

HTML is below.

<div class="normal">
    <p>This is  Paragraph No.1</p>
    <p>This is  Paragraph No.2</p>
    <p>This is  Paragraph No.3</p>
    <p>This is  Paragraph No.4</p>
    <p>This is  Paragraph No.5</p>           
</div>

CSS is below

.normal {
    color: #808080;
    border: 4px solid blue;
    border-radius: 50px 50px;
    width: 800px;
    font-family: 'Comic Sans MS';
    margin: auto;
    margin-top: 10px;
    font-size: 30px;
    -webkit-transform: rotate(10deg);
}

.change {
    color:#ffd800;
    border: 6px solid orange;
    border-radius: 50px 50px;
    width: 800px;
    font-family: 'Comic Sans MS';
    margin: auto;
    margin-top: 10px;
    font-size: 30px;
    -webkit-transform: rotate(20deg);
}

What I want is to toggle my div class between normal and change whenever i click inside the div element. I know how to do it using jQuery but i want to use pure javascript?

Following is my try

(function () {
    var pElement = document.getElementsByClassName("normal");
    pElement.onclick = function () {
       //what to do here
    };
} ());

Advertisement

Answer

getElementsByClassName returns a list of elements, not a single element. So you’ll want to get the first element from it, which actually refers to your div. The code should look something like this:

var pElements = document.getElementsByClassName("normal");
var pElement = pElements[0];
    pElement.onclick = function () {
       if (this.getAttribute("class") == "normal")
         this.setAttribute("class", "change")
       else
         this.setAttribute("class", "normal");
    };

Demo: http://jsfiddle.net/2QqU5/

As RobG mentioned, document.getElementsByClassName() isn’t supported by older browsers still in use. This is mainly IE8 and below. As an alternative, you can use document.querySelectorAll(".normal"). Notice the . in front of the classname (it is a CSS selector). Since you only need one element, you can also use document.querySelector(".normal"), to get just that one element. This might actually be easier, since these are the selectors that jQuery uses as well, so it might be easier to switch back and forth between native an jQuery.

And you can set the class using the className property, instead of using get/setAttribute.

Bringing all that together, the updated code looks like this:

var pElement = document.querySelector(".normal");
    pElement.onclick = function () {
       if (this.className == "normal")
         this.className = "change";
       else
         this.className = "normal";
    };

Updated demo: http://jsfiddle.net/2QqU5/2/

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement