I can not modify the width of a div with JS


Good morning,

I am using a small script to modify the width of a div, which is repeated several times.

$(function() {
   var ancho_div = document.getElementsByClassName("seccion_logro")[0].offsetWidth;
   var ancho_imagen = document.getElementsByClassName("imagen_logro")[0].offsetWidth;
   var ancho_info_logro = ancho_div - ancho_imagen-1; //el -1 es porque sino se pasa a la otra línea
   var d = document.getElementsByClassName('info_logro')
   console.log(ancho_info_logro) //valor del ancho calculado 344px

   document.getElementsByClassName('info_logro')[0].offsetWidth = ancho_info_logro+"px";
   console.log(document.getElementsByClassName('info_logro')[0].offsetWidth); //Valor de 336px cuando debería ser 344px

   for (var i=0; i<d.length; i=i+1) {
      d[i].offsetWidth = ancho_info_logro + "px";


In CSS I have assigned the class info_logro :

.info_logro {
   width: 80%;

I do not see where the error is.

asked by JetLagFox 02.04.2017 в 16:14

1 answer


You should not modify offsetWidth . You must modify style.width .

Instead of

d[i].offsetWidth = ancho_info_logro + "px";

try with

d[i].style.width = ancho_info_logro + "px";
answered by 02.04.2017 / 16:21