I am converting a jQuery site to vanilla javascript and am reaching out for advice on the best way to convert a simple line of jQuery to javascript.
The jQuery
$(".div_class").css({ display: 'none' });
Any suggestions doing this in pure javascript using only classes would be very helpful.
Thanks
-
Possible duplicate of Change the style of an entire CSS class using javascriptthatOneGuy– thatOneGuy2016年03月18日 14:26:19 +00:00Commented Mar 18, 2016 at 14:26
3 Answers 3
Try to use document.getElementsByName
to get the required element,
[].slice.bind(document.getElementsByClassName("div_class"))().forEach(function(itm){
itm.style.display = "none";
});
And convert it to an array by binding the array like object as a this
value of slice
and call it. Now iterate over the returned array and set its display property.
Also you can shorten it by using forEach
directly,
[].forEach.bind(document.getElementsByClassName("div_class"),function(itm){
itm.style.display = "none";
})();
6 Comments
slice()
step: [].forEach.call(document.getElementsByClassName('div_class'), function (el) { el.style.display = 'none'; });.bind
isn't even necessary, since the first argument of .call
sets the context in which [].forEach
is called. .call
further saves the step of having to execute the bound forEach
function at the end: .call
both sets the context and executes the function in one step. :)Select all elements with that class name :
var allEls = document.getElementsByClassName('div_class');
This comes back with an array so you'll have to loop through each element and change each display
to none
like so :
for(var i=0; i < allEls.length; i++){
allElls[i].style.display = 'none'
}
1 Comment
Try these lines to do so:
var div_class = document.getElementsByClassName('div_class');
for (var div in div_class) {
div.style.display = 'none';
}
I think your confusion is because document.getElementsByClassName('div_class')
returns one Array
... and because that I've used a for..in
-loop to iterate over each match of the previous array.
Hope it helps.