Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery CSS to pure Javascript

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?


1 Answers

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';
});

JS Fiddle

like image 174
Harish Kommuri Avatar answered Dec 06 '25 10:12

Harish Kommuri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!