How to get all elements of a specific HTML tag in javascript?

I need to hide all the elements of the "section" section in my document, except for one with a specific identifier.

In jquery it will be easy

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

How can I do this without jquery ??

(I need this to happen as soon as the page loads and is not visible). I also need it to work with a cross browser.

Thank.

+5
source share
2 answers

Put the following immediately before </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>

or in modern browsers (HTML5):

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

DOMElement.getElementsByTagName is your friend:

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";
}
+21
source

All Articles