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>
精彩评论