如何在 javascript 中获取特定 HTML 标签的所有元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6842710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:24:52  来源:igfitidea点击:

How do I get all elements of a particular HTML tag in javascript?

javascript

提问by Tom

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

除了具有特定 ID 的元素之外,我需要隐藏文档中所有类型为“section”的元素。

In jquery this would be easy

在 jquery 中,这很容易

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

How would I do this without jquery??

如果没有 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.

(我需要它在页面加载后立即发生并且不会引起注意)。我还需要它跨浏览器工作。

Thanks.

谢谢。

回答by Jacob Relkin

DOMElement.getElementsByTagNameis your friend:

DOMElement.getElementsByTagName是你的朋友:

var sections = document.getElementsByTagName('section');
var mySection = null;
for(var i = 0; i < sections.length; ++i) {
   if(sections[i].id === "myId") {
      mySection = sections[i];
      mySection.style.display = "block";
      break;
   }
   sections[i].style.display = "none";
}

回答by HBP

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

将以下内容紧邻 HTML 中的 </body> 之前

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

or in "modern" (HTML5) browsers :

或在“现代”(HTML5)浏览器中:

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