0

I found this function:

document.getElementsByClassName = function(c){
    for(var i=0,a=[],o;o=document.body.getElementsByTagName('*')[i++];){
        if(RegExp('\\b'+c+'\\b','gi').test(o.className)){
            a.push(o);
        }
    }

    return a;
}

How can I hide all elements by class?

I tried:

var array = document.getElementsByClassName("hide");

for(var i = 0; i < array.length; i++)
{
    $(array[i]).hide();
}

But I got error:

Could not convert JavaScript argument arg 0 [nsIDOMWindow.getComputedStyle]
4

3 回答 3

4

jQuery allows CSS selectors to be used, doing away with the need for hand-built loops and regular expressions. To hide an element with class fooey, just do

$('.fooey').hide();
于 2012-05-08T19:45:12.067 回答
2

If you're using vanilla JavaScript, then:

var array = document.getElementsByClassName("hide");

for(var i = 0; i < array.length; i++)
{
    array[i].style.display = 'none';
    array[i].onclick = function(){
        // do stuff
    };
    /* or:
    array[i].addEventListener('click',functionToCall);
    */
}

But, given that you're using jQuery, I don't understand why you're complicating things for yourself, just use:

$('.hide').hide();

Further to the above, given your comment:

Because I must add event "click" for each element.

Simply use:

$(elementSelector).click(
    function(){
        // do stuff
    });

Assuming you want to hide, and bind a click-event to, the same elements:

$('.hide').hide().click(
    function(){
        // do stuff
    });
于 2012-05-08T19:45:27.670 回答
2

What you get from getElementsByClassName is NOT an array, but a NodeList, hence the error when trying to loop.

However, you can still loop over a NodeList using the following:

var nodeList = document.getElementsByClassName("hide");
for(var x in nodeList){}
于 2012-05-08T19:45:36.827 回答