Changing the class of a div when clicking on it?

前端 未结 5 1503
时光说笑
时光说笑 2020-12-18 07:39

How can I change a div class name when clicking on it? Eg:

<
相关标签:
5条回答
  • 2020-12-18 07:42

    You have to use an if-statement to reverse it. Here's an example:

    function change_autorefreshdiv(){
        var NAME = document.getElementById("first_name")
        var currentClass = NAME.className;
        if(currentClass == "second_name"){
            NAME.className = "first_name";
        } else {
            NAME.className = "second_name";
        }
    } 
    
    0 讨论(0)
  • 2020-12-18 07:56

    That's because there is no code to do so. Add a little check. I also added some semicolons. I wonder if your script would even work the first time.

    <script language="javascript"> 
    function change_autorefreshdiv(){
      var NAME = document.getElementById("first_name");
      if (NAME.className==="second_name")
      {
        NAME.className="first_name";
      }
      else
      {
        NAME.className="second_name";
      }
    }   
    </script>
    
    0 讨论(0)
  • 2020-12-18 07:59

    A quite late answer, but the reaction marked as answer can be shortened:

    function change_autorefreshdiv(){
         var NAME = document.getElementById("first_name");
         NAME.className = (NAME.className == "second_name") ? "first_name" : "second_name";
    }
    

    This is a shortened notation of the if-else structure. It checks if the className is equal to "second_name". If it is, the currentClass variable will become "first_name", if it's not (meaning it's "first_name"), it will become "second_name".

    0 讨论(0)
  • 2020-12-18 08:00

    simple javascript function, put it in your application.js, or script tag :- (jQuery should be included to run the following function)

    function changeClass(){
            $("#first_name").attr("class", "class-name-you-want-to-assign");
        }
    
    0 讨论(0)
  • 2020-12-18 08:08

    You have to define the second class name. Currently, you have got a function which changes the class name to a hard-coded value, independent on the current class name. See also: MDN: if...else

    function change_autorefreshdiv(){
        var NAME = document.getElementById("first_name");
        var currentClass = NAME.className;
        if (currentClass == "second_name") { // Check the current class name
            NAME.className = "first_name";   // Set other class name
        } else {
            NAME.className = "second_name";  // Otherwise, use `second_name`
        }
    }   
    
    0 讨论(0)
提交回复
热议问题