jQuery .hasClass() method fails for SVG elements

后端 未结 5 1837
挽巷
挽巷 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:28

    This is not the fastest option ever, but it is a possible solution. Instead of using jQuery's hasClass you could instead obtain the class attribute as a string and use indexOf to search through it. There are probably use cases where this will fail, so I wouldn't recommend this except for super simple projects.

    Working example:

    var s = $(this).attr('class');
    if( s.indexOf('node')!==-1 ){
        // do something
    }
    

    Remember: indexOf returns -1 when it can't find anything, not 0. 0 is returned when the substring starts at index 0.

提交回复
热议问题