提问人:Lavert 提问时间:10/25/2023 最后编辑:Lavert 更新时间:10/25/2023 访问量:35
HTML 集合 - 将类添加到第一个 div [duplicate]
HTML Collection - add class to first div [duplicate]
问:
我正在使用 getElementsByClassName 通过其唯一的类名选择单个 div。出于某种原因,使用 querySelector 无法通过其唯一的类名来选择此 div,它会返回“null”。
我正在尝试使这个单个 div 要么显示:none,添加/删除一个类,要么只是不可见,我现在并不在乎。它返回一个 HTML 集合,其中包含正确的单个 div,因此长度为 1,我想要的 div 位于位置 0。每次我尝试从集合中访问此 div 时,我都会得到空。
所以这段代码:
let eleList = document.getElementsByClassName("CustomFormFieldQuestion_252145870712756");
console.log(eleList);
console.log(eleList.item(0));
在控制台中返回给我这个:
HTMLCollection { length: 0 }
0: <div class="at-row at-row-full Custo…uestion_252145870712756">
length: 1
<prototype>: HTMLCollectionPrototype { item: item(), namedItem: namedItem(), length: Getter, … }
null
div is it grabbing 是正确的 div;但是,当我尝试访问它以添加类或为其提供 style.display = “none” 时,我在控制台中得到的只是“null”。
我有一个列表,其中包含大约 10 个项目,我需要按它们的唯一类抓取它们,在页面初始化时隐藏它们,然后根据上一个问题中的复选框响应使它们可见。
我尝试将 HTML 集合转换为数组并以这种方式访问它,
let arrayEleList = Array.from(eleList);
它返回了一个空数组。
我在这里做错了什么,最初的 eleList 返回正确的 div,但每当我尝试访问它以执行某些操作时,我都会得到“null”。
答:
// Get the element using querySelector
let ele = document.querySelector(".CustomFormFieldQuestion_252145870712756");
// Check if the element exists
if (ele) {
// You have successfully selected the element
// Now you can manipulate it as needed
// For example, to hide the element:
// ele.style.display = "none";
// Or to add a class:
// ele.classList.add("yourClassName");
} else {
console.log("Element not found");
}
此代码使用 document.querySelector 选择具有指定类名的第一个元素。然后,它会检查该元素是否存在,如果存在,您可以通过更改其 style.display 或添加类来继续操作它。
评论
由于 document.getElementByClassName 返回一个数组,其中包含提供相同类的所有元素。即使类是唯一的,它也会在数组中返回。
为了抓住它,你可以这样做
let elements = document.getElementByClassName("your classname here")
elements.forEach((elem, index) => {
console.log(`index number = ${index} and element = ${elem}`)
})
检查它将像打印的控制台一样
索引号 = 0 和 element = 该类名的元素
请注意,索引号并像这样使用...
let elements = document.getElementByClassName("your classname here")
let index = 0 // replace the index number shown in previous code
console.log(elements[index])
现在你可以继续了。
如果你有一个唯一的类,那么你可以使用 querySelector
确保没有同一类的其他元素。如果有多个元素具有相同的类,那么它将返回具有该类的 html 中的第一个元素,其他元素将被忽略。如果要访问所有元素,则可以使用 querySelectorAll。
请记住,如果使用 VS Code,则使用 querySelector 不会提供任何建议。
let elem = document.querySelector(".CustomFormFieldQuestion_252145870712756")
// Now you can do manipulation on it like here
elem.style.display = "none"
如果您仍然收到未定义的错误,则意味着类名错误或未正确加载 HTML DOM。
如果还有更多错误,请提供完整的代码以获得正确的解决方案。
评论