jQuery .hasClass() method fails for SVG elements

后端 未结 5 1836
挽巷
挽巷 2021-02-18 14:51

I have a set of SVG elements with the classes node and link. My program should detect whether an element has the node class or the l

5条回答
  •  你的背包
    2021-02-18 15:19

    This is a hack for addClass, removeClass, hasClass jquery methods for before jquery 3.x.x versions.

    $.fn.extend({
        addSVGClass: function (cls) {
            return this.each(function () {
                var classList = $(this).attr('class');
                if (classList) {
                    var classListArr = classList.split(" ");
                    if (classListArr.indexOf(cls) === -1) {
                        classListArr.push(cls);
                        classList = classListArr.join(" ").trim();
                        $(this).attr('class', classList);
                    }
                } else {
                    $(this).attr('class', cls);
                }
            });
        },
        removeSVGClass: function (cls) {
            return this.each(function () {
                var classList = $(this).attr('class');
                if (classList) {
                    var classListArr = classList.split(" ");
                    if (classListArr.indexOf(cls) !== -1) {
                        delete classListArr[classListArr.indexOf(cls)];
                        classList = classListArr.join(" ").trim();
                        $(this).attr('class', classList);
                    }
                }
    
            });
        },
        hasSVGClass: function (cls) {
            var el = this[0];
            var classList = $(el).attr('class');
            if (classList) {
                var classListArr = classList.split(" ");
                if (classListArr.indexOf(cls) !== -1) {
                    return true;
    
                } else {
                    return false;
                }
            }
            return false;
        }
    });
    

    usage :

    $('.svg-element').addSVGClass('selected');
    

提交回复
热议问题