Monday, June 3, 2024
33
rated 0 times [  40] [ 7]  / answers: 1 / hits: 171304  / 10 Years ago, sat, march 8, 2014, 12:00:00

I would like to know how to select all elements with class names widget and hover and then remove class hover from these elements.



I have the following JavaScript code that selects all elements with class widget and hover:



var elements = document.getElementsByClassName('widget hover');
console.log(elements);


This seems to work and outputs something like this (with no errors):



[div#.widget... 


The problem is that if I try to remove the class hover, I get an error:



var elements = document.getElementsByClassName('widget hover');
console.log(elements);
elements.classList.remove(hover);


This outputs:



[item: function]
length: 0
Uncaught TypeError: Cannot call method 'remove' of undefined


Can anyone tell me what I'm doing wrong?





Please note that I have it working in jQuery:



$('.widget.hover').removeClass('hover');


... but I'm looking for a solution in pure JavaScript.


More From » getelementsbyclassname

 Answers
0
var elems = document.querySelectorAll(.widget.hover);

[].forEach.call(elems, function(el) {
el.classList.remove(hover);
});





You can patch .classList into IE9. Otherwise, you'll need to modify the .className.



var elems = document.querySelectorAll(.widget.hover);

[].forEach.call(elems, function(el) {
el.className = el.className.replace(/bhoverb/, );
});


The .forEach() also needs a patch for IE8, but that's pretty common anyway.


[#72091] Thursday, March 6, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
willieelisham

Total Points: 201
Total Questions: 108
Total Answers: 106

Location: Zambia
Member since Sat, Oct 31, 2020
4 Years ago
willieelisham questions
Wed, Apr 14, 21, 00:00, 3 Years ago
Wed, Mar 31, 21, 00:00, 3 Years ago
Sun, Oct 11, 20, 00:00, 4 Years ago
Sat, May 9, 20, 00:00, 4 Years ago
;