在不使用JQuery的情况下隐藏DOM中的选定元素

Hide selected elements from the DOM without JQuery

本文关键字:DOM 元素 隐藏 情况下 JQuery      更新时间:2023-09-26

以下代码在原生JS中是什么样子的?

$(".custom-popover").hide();

这个问题有点宽泛。jQuery内部是这样做的,然后还有一种方法,你可以只使用原生JavaScript,而不依赖于jQuery的方式:

[].slice.call(
    document.querySelectorAll('.custom-popover')).forEach(function (el) {
        el.style.display = 'none';
    }
);

由于document.querySelectorAll返回一个不能与forEach一起使用的nodelist,因此可以通过在nodelist上调用slice将其转换为实际数组。之后,遍历所有找到的内容并更新style属性。


这是一个不使用forEach替代方案,尽管我更喜欢上面的方法:

var els = document.querySelectorAll('.custom-popover');
for (var i = 0; i < els.length; i++) {
    els[i].style.display = 'none';
}