你不应该为此使用 for-in 循环。
document.getElementsByClassName('someClass')
返回一个NodeList,它不继承自Array.prototype
,但在某些方面是相似的。就像名字所说的,它是一个节点列表。这意味着它有一个length
属性,并且只能使用以下方式访问:
var myElements = document.getElementsByClassName('yourClass');
for (var i = 0, ii = myElements.length; i < ii; i++) {
console.dir(myElements[i].style);
};
这里是你应该如何真正隐藏一个元素。
/**
* Shows or hides an element from the page. Hiding the element is done by
* setting the display property to "none", removing the element from the
* rendering hierarchy so it takes up no space. To show the element, the default
* inherited display property is restored (defined either in stylesheets or by
* the browser's default style rules.)
*
* Caveat 1: if the inherited display property for the element is set to "none"
* by the stylesheets, that is the property that will be restored by a call to
* showElement(), effectively toggling the display between "none" and "none".
*
* Caveat 2: if the element display style is set inline (by setting either
* element.style.display or a style attribute in the HTML), a call to
* showElement will clear that setting and defer to the inherited style in the
* stylesheet.
* @param {Element} el Element to show or hide.
* @param {*} display True to render the element in its default style,
* false to disable rendering the element.
*/
var showElement = function(el, display) {
el.style.display = display ? '' : 'none';
};
var myElement = document.getElementById('someID');
showElement(myElement, false);// it should now be hidden.