我需要隐藏文档中"section"类型的所有元素,而不是具有特定ID的元素.
在jquery中,这很容易
$("section").hide();
$("section#myId").show();
Run Code Online (Sandbox Code Playgroud)
如果没有jquery,我该怎么做?
(我需要在页面加载时发生并且不会显示).我还需要它跨浏览器工作.
谢谢.
Jac*_*kin 22
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";
}
Run Code Online (Sandbox Code Playgroud)
HBP*_*HBP 14
将以下内容放在HTML中的</ body>之前
<script>
(function () {
for(var els = document.getElementsByTagName ('section'), i = els.length; i--;)
els[i].id !== "myId" && (els[i].style.display = "none");
}) ();
</script>
Run Code Online (Sandbox Code Playgroud)
或者在"现代"(HTML5)浏览器中:
<script>
[].forEach.call (document.querySelectorAll ('section'),
function (el) { el.id !== "myId" && (el.style.display = "none"); })
</script>
Run Code Online (Sandbox Code Playgroud)