js find :invalid inside div 1

js find :invalid inside div

var contactForm = document.getElementById('contact-form');
if (contactForm.checkValidity() == false) {
    var list = contactForm.querySelectorAll(':invalid');
    for (var item of list) {
        item.setAttribute("style", "background-color: red;")

Here is what the above code is Doing:
1. We’re getting the contact form element from the DOM.
2. We’re checking if the form is valid.
3. If the form is not valid, we’re getting all the invalid elements from the form.
4. We’re looping through the invalid elements and setting the background color to red.

Now, let’s add the above code to the script.js file.

Similar Posts