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]
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]
Share
Improve this question
asked May 8, 2012 at 19:42
NeverNever
3232 gold badges7 silver badges24 bronze badges
9
-
6
Seeing as you're using jQuery, why aren't you just doing
$('.classname').hide()
? – Bojangles Commented May 8, 2012 at 19:43 - Because I must add event "click" for each element. – Never Commented May 8, 2012 at 19:45
-
This seems like a lot of writing for something that could be done with
$(".hide").hide()
? – adeneo Commented May 8, 2012 at 19:45 - Why do you want to add a click event to something that's being hidden? – Bojangles Commented May 8, 2012 at 19:46
-
Then just do
$(".hide").hide().on('click', function() { $(this).show(); });
etc ??? – adeneo Commented May 8, 2012 at 19:47
3 Answers
Reset to default 4jQuery 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();
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 plicating things for yourself, just use:
$('.hide').hide();
Further to the above, given your ment:
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
});
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){}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744853558a4597270.html
评论列表(0条)