I am trying to use jQuery as little as possible and I would like to translate some jQuery code to pure JS.
I have this:
$(".myDiv").css({"width": 500});
What is the pure JS equivalent of the code above?
var els = document.querySelectorAll('.myDiv');
// If you want to get elements using its class name
// var els = document.getElementsByClassName('myDiv');
for(var i = 0, length = els.length; i < length; i++) {
els[i].style.width = '500px';
}
By using forEach:
var els = document.querySelectorAll('.myDiv');
els.forEach(function(el, ind) {
el.style.width = '500px';
});
for loop should be for(var i = 0, length = els.length; i < length; i++). It is faster than acessing the length property all the time.There are a few ways to achieve the same affect, but you could go with something like this:
document.querySelectorAll('.myDiv').forEach(function(el) {
el.style.width = '500px';
});
querySelectorAll selects all of a particular CSS selector as a collection of DOM elements. forEach iterates through the collection, passing the currently selected element to the inner function, which is then styled with style.width.
document.querySelectorAll('.myDiv').forEach(function(elem) {
elem.style.width = "500px";
})
querySelectorAll gets the elements, then you iterate over the elements and set the style for each one.
You just need to use document.getElementsByClassName() to get all the elements with this class and then iterate over them and use style.width to change their width:
Array.from(document.getElementsByClassName("myDiv")).forEach(function(div) {
div.style.width = "500px";
});
Demo:
Array.from(document.getElementsByClassName("myDiv")).forEach(function(div) {
div.style.width = "100px";
});
.myDiv{
background-color:yellow;
}
<div class="myDiv">A</div>
Note:
We use Array.from() to treat the result of document.getElementsByClassName as an Array as it's returned as a Nodelist or an array-like object and doesn't have the Array properties and the .forEach method in older browsers.