How do i toggle between classes of an element using javascript?

This question already has an answer here:

  • Change an element's class with JavaScript 30 answers

  • JavaScript

    function toggleClass(element, origin, target) {
        var newClass = element.className.split(" ");
        for (var i = 0, i < newClass.length; i++) {
            if (origin.localeCompare(newClass[i]) == 0) {
                newClass[i] = target;
            };
        };
        element.className = newClass.join(" ");
    };
    // Usage
    var img = document.getElementById("img1");
    toggleClass(img, "img1 img2");
    

    jQuery

    $("#img1").toggleClass("img1 img2");
    

    More here.


    function test() {
        t1.className = t1.className == 'img1' ? 'img2' : 'img1';
    }
    

    相关:使用JavaScript更改元素的类


    If you are not using jQuery I will suggest you 2 things:

  • With onclick property, you don't need to set javascript: before calling a function. It will not work if you use it.
  • You can send the element through the function like this: onclick=test(this) . Now you will only have to compare his class.
  • function testFunction(element) {
        if (element.className === 'img1') {
            element.className = 'img2';
        } else {
            element.className = 'img1';
        }
    }

    TAKE CARE if you use multiclasses, because you will need to add them into the classname. This function will remove full class name for the new one.

    链接地址: http://www.djcxy.com/p/25212.html

    上一篇: 通过ID更改HTML元素

    下一篇: 如何在使用javascript的元素的类之间切换?