Check if an element contains a class in JavaScript?

后端 未结 27 2730
面向向阳花
面向向阳花 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:19

    in which element is currently the class '.bar' ? Here is another solution but it's up to you.

    var reg = /Image/g, // regexp for an image element
    query = document.querySelector('.bar'); // returns [object HTMLImageElement]
    query += this.toString(); // turns object into a string
    
    if (query.match(reg)) { // checks if it matches
      alert('the class .bar is attached to the following Element:\n' + query);
    }
    

    jsfiddle demo

    Of course this is only a lookup for 1 simple element (/Image/g) but you can put all in an array like

  • is /LI/g,
      = /UL/g etc.

提交回复
热议问题