0

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 jQuery?

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

Flimm
  • 136,138
  • 45
  • 251
  • 267
  • A ` – Flimm Jul 09 '23 at 13:04
  • My comment seemed to have been moved to this question: https://stackoverflow.com/q/70011109/247696 So I'm posting a comment again to the best of my recollection (see previous comment). (Honestly, my memory may be faulty, but that was my intention, any way) – Flimm Jul 09 '23 at 13:05
  • I suppose the dupe target could get changed to https://stackoverflow.com/q/70011109/247696 – Flimm Jul 09 '23 at 13:06

2 Answers2

1

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
}
Flimm
  • 136,138
  • 45
  • 251
  • 267
1

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

Samson Iyanda
  • 512
  • 3
  • 13