2011-07-27 34 views
5

Tôi cần phải ẩn tất cả các thành phần của loại 'phần' trong tài liệu của tôi ngoài một phần tử có ID cụ thể.Làm cách nào để có được tất cả các phần tử của một thẻ HTML cụ thể trong javascript?

Trong jquery này sẽ dễ dàng

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

Làm thế nào tôi có thể làm điều này mà không jquery ??

(Tôi cần nó xảy ra ngay khi tải trang và không đáng chú ý). Tôi cũng cần nó để làm việc qua trình duyệt.

Cảm ơn.

Trả lời

12

Đặt sau ngay trước </body > trong HTML của bạn

<script> 
(function() { 
    for(var els = document.getElementsByTagName ('section'), i = els.length; i--;) 
    els[i].id !== "myId" && (els[i].style.display = "none"); 
})(); 
</script> 

hay "hiện đại" (HTML5) trình duyệt:

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

DOMElement.getElementsByTagName là bạn của bạn:

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"; 
} 
Các vấn đề liên quan