admin管理员组

文章数量:1336281

What's the problem in my code?

Uncaught TypeError: Cannot read properties of undefined (reading 'remove')

and

Uncaught TypeError: Cannot read properties of undefined (reading 'add')

document.querySelector("#elastic").oninput = function () {
    let val = this.value.trim();
    let elasticItem = Array.from(document.querySelectorAll(".elastic li"));
    if (val != "") {
        elasticItem.forEach(function (elem) {
            if (elem.innerText.search(val) === -1) {
                elem.classlist.add("hide");
            } else {
                elem.classlist.remove("hide");
            }
        });
    }
};
.hide {
  display: none;
}
<div>
    <input type="text" id="elastic" placeholder="Search" />
</div>

<div>
    <ul class="elastic">
        <li>ht</li>
        <li>sdf</li>
        <li>qwe</li>
        <li>cxv</li>
        <li>sad</li>
        <li>sdf</li>
        <li>dfg</li>
    </ul>
</div>

What's the problem in my code?

Uncaught TypeError: Cannot read properties of undefined (reading 'remove')

and

Uncaught TypeError: Cannot read properties of undefined (reading 'add')

document.querySelector("#elastic").oninput = function () {
    let val = this.value.trim();
    let elasticItem = Array.from(document.querySelectorAll(".elastic li"));
    if (val != "") {
        elasticItem.forEach(function (elem) {
            if (elem.innerText.search(val) === -1) {
                elem.classlist.add("hide");
            } else {
                elem.classlist.remove("hide");
            }
        });
    }
};
.hide {
  display: none;
}
<div>
    <input type="text" id="elastic" placeholder="Search" />
</div>

<div>
    <ul class="elastic">
        <li>ht</li>
        <li>sdf</li>
        <li>qwe</li>
        <li>cxv</li>
        <li>sad</li>
        <li>sdf</li>
        <li>dfg</li>
    </ul>
</div>

Share edited Jan 16, 2022 at 19:22 Nice18 5662 silver badges12 bronze badges asked Jan 15, 2022 at 6:35 AKAENOAKAENO 431 gold badge1 silver badge3 bronze badges 2
  • 2 just change classlist to classList – Saeed Shamloo Commented Jan 15, 2022 at 6:37
  • You can use hidden attribute instead. elem.hidden = true for hiding an element and elem.hidden = false for showing an element. – Nice18 Commented Jan 15, 2022 at 7:11
Add a ment  | 

1 Answer 1

Reset to default 3

JavaScript is case-sensitive

Change
classlist to classList (lL)

elem.classList.add('hide');
elem.classList.remove('hide');

本文标签: javascriptUncaught TypeError Cannot read properties of undefined (reading 39remove39)Stack Overflow