skip to Main Content

I’m thring to convert this code to vanilla JavaScript without jQuery:

if ($(el).is(":invalid")) {
  // etc
}

How do I write this code without using JavaScript?

I tried looking at youmightnotneedjquery.com , but it doesn’t seem to have this use-case.

2

Answers


  1. Chosen as BEST ANSWER

    You can use the matches function, and pass to it any CSS selector that would work with any pseudo-class, including :invalid:

    if (el.matches(":invalid")) {
      // etc
    }
    

  2. You can simply check the ‘validity.valid’ property of the element.

    const el = document.getElementById('elementId');
    
    // check it's not valid
    if(!el.validity.valid) {
      // ...
    }
    

    Read more about this property on MDN

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search