Skip to content Skip to sidebar Skip to footer

How To Check Class Of Multiple Class Elements In Javascript, Without Jquery

I have the following javascript code to put the uploader name before the upload date and view count in youtube search results. function hasClass(element, cls) { return (' ' + e

Solution 1:

element.classList

It would return you the array of all the classes present on the element like ["site-icon", "favicon", "favicon-stackoverflow"] , so then by using normal javascript you can implement hasClass functionality of your own.

So your hasClass function becomes

functionhasClass(element, cls){
  return element.classList.contains(cls);
}

Solution 2:

You can use classList but this is not supported in all browsers.

I think the best solution is something like that:

functionhasClass (element, cls) {
    var classes = element.className.split(' ');
    return classes.indexOf(cls) != -1;
}

Post a Comment for "How To Check Class Of Multiple Class Elements In Javascript, Without Jquery"