首页 > 解决方案 > 从父元素的子元素获取类值

问题描述

以下部分代码来自我在 YouTube 上找到的快速表单验证教程。checkInputs()如果函数中的所有formControl类名 = form-control success,我正在尝试创建一个附加功能以在函数内部生成成功消息setSuccessFor(input)。我创建了一个allEl将 转换allElementsNode为数组的变量,但我似乎无法遍历它来提取孩子的类名。所以[...allElementsNode][0]让我可以访问父表单元素,所以我要做的是遍历所有子 div 以获取类值以比较它是否等于form-control success. 如果我尝试迭代allEl,我会得到undefined.

HTML

 <form class="form" id="form">
                <div class="form-control">
                    <label>Username</label>
                    <input type="text" placeholder="Angel" id="username">
                    <i class="fa fa-check-circle"></i>
                    <i class="fa fa-exclamation-circle"></i>
                    <small>Error message</small>
                </div>
                <div class="form-control">
                    <label>Email</label>
                    <input type="email" placeholder="angel@gmail.com" id="email">
                    <i class="fa fa-check-circle"></i>
                    <i class="fa fa-exclamation-circle"></i>
                    <small>Error message</small>
                </div>
                <div class="form-control">
                    <label>Password</label>
                    <input type="password" placeholder="password" id="password">
                    <i class="fa fa-check-circle"></i>
                    <i class="fa fa-exclamation-circle"></i>
                    <small>Error message</small>
                </div>
                <div class="form-control">
                    <label>Password check</label>
                    <input type="password" placeholder="Password two" id="password2">
                    <i class="fa fa-check-circle"></i>
                    <i class="fa fa-exclamation-circle"></i>
                    <small>Error message</small>
                </div>
                <button>Submit</button>
            </form>

JavaScript

const form = document.querySelector('#form');
const username = document.querySelector('#username');
const email = document.querySelector('#email');
const password = document.querySelector('#password');
const password2 = document.querySelector('#password2');
let allElementsNode = document.querySelectorAll("#form");
const allElementsArray = Array.from(allElementsNode);
let formControl;

form.addEventListener('submit', (e) => {
    e.preventDefault();
    checkInputs();
});

function checkInputs() {
    // get values from the inputs
    const usernameValue = username.value.trim();
    const emailValue = email.value.trim();
    const passwordValue = password.value.trim();
    const password2Value = password2.value.trim();

    if (usernameValue === '') {
        // show error
        setErrorFor(username, 'Username cannot be blank');
    } else {
        // show success
        setSuccessFor(username);
    }
    if (emailValue === '') {
        // show error
        setErrorFor(email, 'Email cannot be blank');
    } else if (!isEmail(emailValue)) {
        setErrorFor(email, 'Email is not valid')
    } else {
        // show success
        setSuccessFor(email);
    }
    if (passwordValue === '') {
        // show error
        setErrorFor(password, 'Passwords cannot be blank');
    } else {
        // show success
        setSuccessFor(password);
    }
    if (password2Value === '' || password2Value !== passwordValue) {
        // show error
        setErrorFor(password2, 'Passwords cannot be blank and must match!');
    } else {
        // show success
        setSuccessFor(password2);
    }
    // Set success message. All formControl should have the success class set
    // console.log(formControl.className)
    const allEl = [...allElementsNode][0];
    console.log(allEl);
    const allCtrlEl = Array.from(allEl).forEach(item => item);
    console.log(allCtrlEl);
}

function setErrorFor(input, message) {
    formControl = input.parentElement; // .form-control
    const small = formControl.querySelector('small');

    // add error message inside small
    small.innerText = message;
    // add error class
    formControl.className = 'form-control error';
}

function setSuccessFor(input) {
    formControl = input.parentElement; // .form-control
    formControl.className = 'form-control success';
}

function isEmail(email) {
    const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    return emailPattern.test(email); 
}

在此处输入图像描述

标签: javascriptparent-childnodelist

解决方案


看起来您的 allElementsNode 是父表单,因此您需要像这样获取 childrenElements

const allEl = [...allElementsNode.children];

推荐阅读