Check if an element contains a class in JavaScript?

后端 未结 27 2800
面向向阳花
面向向阳花 2020-11-22 09:36

Using plain JavaScript (not jQuery), Is there any way to check if an element contains a class?

Currently, I\'m doing this:

27条回答
  •  忘了有多久
    2020-11-22 10:03

    This is a bit off, but if you have an event that triggers switch, you can do without classes:

    You can do

    $('body').click( function() {
    
        switch ( this.id.replace(/[0-9]/g, '') ) {
            case 'classOne': this.innerHTML = "I have classOne"; break;
            case 'classTwo': this.innerHTML = "I have classTwo"; break;
            default: this.innerHTML = "";
        }
    
    });
    

    .replace(/[0-9]/g, '') removes digits from id.

    It is a bit hacky, but works for long switches without extra functions or loops

提交回复
热议问题