简体   繁体   English

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

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

I need to hide all elements of type 'section' in my document apart from one with a particular ID. 除了具有特定ID的元素外,我需要在文档中隐藏所有“节”类型的元素。

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. 谢谢。

DOMElement.getElementsByTagName is 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";
}

Place the following immediately before the </body> in your 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM