在没有JQuery的情况下隐藏DOM中的选定元素

时间:2016-05-19 14:45:44

标签: javascript jquery

以下代码在本机JS中的外观如何?

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

1 个答案:

答案 0 :(得分:2)

这个问题有点广泛。 jQuery内部有这样的方式,然后有一种方法可以使用本机JavaScript来完成它,而不管jQuery如何做到这一点:

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

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

这是一个不使用var els = document.querySelectorAll('.custom-popover'); for (var i = 0; i < els.length; i++) { els[i].style.display = 'none'; } 替代,但我更喜欢上述方法:

(TF as ILinkable).BugLinkFactory;