9

I know this setup I have isn't ideal however I need to check the class of an input element. I have just started using Vue.js on a new project however we have a form validation library that has to be used that uses jQuery.

The validation library I am using adds a class to an input if it doesn't fit some validation requirements.

If I was using jQuery I could just use hasClass to check if the input element had a specific class.

In Vue I am unsure how I can check if an element has a class though?

Here is an example method of what I'd like to achieve:

      methods: {
        nextStep: function() {
          const element = this.$el.querySelector("#conversation__tram-1 input");
          if (element has the class of is-valid) {
            Do something
          }

        },
      },

As you can see I'd like to check whether or not the input field has a class of is-valid. Can you think of any way I can do this with Vue.js? Thanks.

1
  • Another thing you can use to make this code more Vue-like is ref for the element: vuejs.org/v2/api/#ref Commented May 30, 2017 at 16:55

3 Answers 3

18

You can use the element's classList property:

if (element.classList.contains('is-valid')) {
  // Do something
}
Sign up to request clarification or add additional context in comments.

2 Comments

If you don't need IE9 support then you're good: caniuse.com/#search=classList
Yeah, if you really need IE9 support, there's a Polyfill you can use on the page I linked.
1

Most of the native vue.js functions involve manipulating the data behind the DOM, not the DOM itself.

There are multiple ways you can achieve this,
You can use Vue class binding, which is two-way. So you once you initialize binding then you can build an API to expose that.

Have you tried this?

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

Comments

1

If jQuery is already involved, just use its hasClass the way you already know how.

    nextStep: function() {
      const element = this.$el.querySelector("#conversation__tram-1 input");
      if ($(element).hasClass('is-valid')) {
        Do something
      }
    },

Vue does not provide any special DOM manipulation routines, because in Vue, you aren't generally supposed to be manipulating the DOM. There are some carved-out exceptions, but this isn't really one. :) The key to mixing jQuery and Vue is that you must be careful to separate what jQuery controls from what Vue controls so they don't step on each other's toes. Not much harm here in simply reading the DOM as long as you don't expect Vue to be updating it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.