-4
<div class="button button1" onclick="toggleClass();">Stay Updated</div>

    <script>
        function toggleClass(){
            if(className == "button button1"){
                    className = "info";
          } else {
                    className = "button button 1";
}

    </script>

Trying to change the class of the div on clicking the div. The div is meant to act like a button which should be replaced by another div class. This is my coding so far, please help. Thanks in advance.

  • Assigning a variable called `className` does not automatically change the class of the div tag. Do a little research and you will figure it out. – Rick S Feb 03 '17 at 20:02
  • You might want to check out this [link](http://stackoverflow.com/questions/195951/change-an-elements-class-with-javascript). The class name exists in the DOM. You can't change it as if it were local to your code. – rasmeister Feb 03 '17 at 20:02

1 Answers1

0

You have several issues with your code. First, you're missing a closing bracket } in your if/else statement. Check your console, F12 to see the error:

Uncaught SyntaxError: Unexpected end of input

Secondly, as noted above in the comments, className doesn't automatically exist and doesn't change the classes of the elements. className is a property of the DOM object. You'll need to get the clicked element and reference the className property to retrieve and set this correctly.

Before you can do that however, you need to get the clicked element. To do this, add the event parameter to your inline click handler:

onclick="toggleClass(event);"

and reference the event object in your function toggleClass:

function toggleClass(evt) {

Use the target property of the event object to find the clicked element and save it off into a variable:

var btn = evt.target;

Finally, reference btn.className in place of all of the className references you have in your function.

DEMO:

function toggleClass(evt) {
    var btn = evt.target;
  
    if(btn.className == "button button1") {
        btn.className = "info";
    } else {
        btn.className = "button button1";
    }
}
div {
  color: #fff;  
}
div.button.button1 {
  background: blue;
}
div.info {
  background: green;  
}
<div class="button button1" onclick="toggleClass(event);">Stay Updated</div>
War10ck
  • 12,387
  • 7
  • 41
  • 54