如何在JS中迭代HTML元素的子元素

s5a0g9ez  于 2022-12-02  发布在  其他
关注(0)|答案(2)|浏览(122)
<div class="inputs">
        <input type="text" id="title" placeholder="tilte">
        <div class="price">
            <input type="number" id="price" placeholder="price">
            <input type="number" id="taxes" placeholder="taxes">
            <input type="number" id="ads" placeholder="ads">
            <input type="number" id="discount" placeholder="discount">
</div>

我想把HTML的父“inputs”中的每个元素都迭代到JS中..就像使用(for)或(forEach)而不写每个子元素一样:

let title = document.getelementbyid("title");
let price = document.getelementbyid("price");
h79rfbju

h79rfbju1#

不确定您要实现的目标。也许您希望使用按id的选择器来使您的生活更轻松一些。如果是这样的话,您可能会喜欢以下方法:

const getElementById = (id = "") => {
    return document.getElementById(id);
};

const getElementsById = (ids = []) => {
    return ids.map(getElementById);
};

const getElementsByIdMap = (ids = []) => {
    return Object.fromEntries(ids.map((id) => [id, getElementById(id)]));
};

const getElementValue = (el = {}) => {
    return el?.value;
};

const elements = getElementsById([
    "title",
    "price",
    "taxes",
    "ads",
    "discount",
    "total",
    "count",
    "category",
    "submit",
]);

elements.forEach((el) => {
    console.log(el);
});

const { title, price, taxes, ads, discount, total, count, category, submit } = getElementsByIdMap([
    "title",
    "price",
    "taxes",
    "ads",
    "discount",
    "total",
    "count",
    "category",
    "submit",
]);

const myFormElements = getElementsByIdMap(["title", "price", "taxes", "ads", "discount", "total", "count", "category"]);

getElementById("submit").addEventListener("click", (ev) => {
    ev.preventDefault(); // maybe
    const values = Object.fromEntries(
        myFormElements.keys(myFormElements).map((key) => [key, getElementValue(myFormElements[key])])
    );

    console.log(values);
});

HTML表单最简单的破解方法之一是:

document.getElementById("submitFormId").addEventListener("submit", (event) => {
    event.preventDefault();
    const values = Array.from(event.target)
        .slice(0, 8) // in your case there are 9 elements, last is submit with index 8 so we cut it
        .map((input) => input.value.trim()); // trim all the values to exclude spaces
    console.log(values);
});
wdebmtf2

wdebmtf22#

您可以使用querySelectorAll并通过使用.(例如.my_class)获取类,使用#(例如#my_id)获取id,或者使用不带任何符号的html元素(例如input)获取id。
对于您的情况,要从class .inputs中获取所有元素input,应如下所示:
第一个

相关问题