开发者

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.

In jquery this would be easy

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

How would I do this without jquery??

(I need it to happen as soon as the page loads and to not be noticable开发者_Go百科). I also need it to work cross browser.

Thanks.


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";
}


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>

or in "modern" (HTML5) browsers :

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜