Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tptompkins's avatar

.hasClass() equivalent in Vue?

Hello,

Does anyone know if there is a .hasClass() equivalent in Vue without using vanilla javascript or JQuery?

0 likes
6 replies
zachleigh's avatar

I dont think so. Most of the native vue functions involve manipulating the data behind the DOM, not the DOM itself. Generally, when using vue, you dont actually need to touch the DOM elements, Vue takes care of it for you.

jimmck's avatar

Well you can bind the class property to an element so it can be dynamically set.

1 like
tptompkins's avatar

Thanks. I know that I can set the class dynamically, but in this particular case a different framework is setting different classes on the element dynamically and I'm curious if there's a way that I can watch when specific classes are assigned to that element with Vue.

Dan's avatar

@tptompkins Could you do something like this?

if (this.$els.elementNameHere.className.match(/\bmyclass\b/)) {
    //
}
jimmck's avatar

Well the Vue class binding is two way. Once an elements class property is bound you can build an API to expose that to any classes. The API is an implementation of isClass. Better still you don't have search for elements of a class the API returns them.

zubaer_ahammed's avatar
if (element.classList.contains('myclass')) {
  // Do something
}

Example: add class 'favorite' on click:

toggle_favorite($event) {

    if( !$event.target.classList.contains('favorite') ) {

       //do something like making an ajax call.

    } else {

      //do something like making an ajax call.

    }

   $event.target.classList.toggle('favorite');

}
1 like

Please or to participate in this conversation.