如何在javascript中获取特定HTML标记的所有元素? [英] How do I get all elements of a particular HTML tag in javascript?

查看:70
本文介绍了如何在javascript中获取特定HTML标记的所有元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要隐藏文档中section类型的所有元素,而不是具有特定ID的元素。

I need to hide all elements of type 'section' in my document apart from one with a particular ID.

在jquery中这很容易

In jquery this would be easy

$("section").hide();
$("section#myId").show();

如果没有jquery,我该怎么做?

How would I do this without jquery??

(我需要它在页面加载时发生并且不会显示出来)。我还需要它跨浏览器工作。

(I need it to happen as soon as the page loads and to not be noticable). I also need it to work cross browser.

谢谢。

推荐答案

将以下内容放在< / body>之前。在您的HTML中

Place the following immediately before the </body> in your HTML

<script>
(function () {
  for(var els = document.getElementsByTagName ('section'), i = els.length; i--;)
    els[i].id !== "myId" && (els[i].style.display = "none");
}) ();
</script>

或现代(HTML5)浏览器:

or in "modern" (HTML5) browsers :

<script>
  [].forEach.call (document.querySelectorAll ('section'),
    function (el) { el.id !== "myId" && (el.style.display = "none"); })
</script>

这篇关于如何在javascript中获取特定HTML标记的所有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆