Search code examples
javascripthtmlcssclassname

Cannot append style to div using veriable


I can append a style inline when using a string like so

element.style.width='100px';

However it does not append if i use a variable like so

    //get ID of clicked elemnt
    var divId = cssPath(e.target).substring(1);
    var tagetDiv = document.getElementById(divId);
    var targetWidth = tagetDiv.clientWidth;

    var overlayDiv = document.createElement('div');
    overlayDiv.className = 'bsOverlay';
    overlayDiv.style.width=targetWidth;

Solution

  • clientWidth is a number.

    The CSS width property requires a unit (typically px).

    You need to concatenate it:

    overlayDiv.style.width = targetWidth + 'px';