skip to Main Content

I have an input elements whose width is set as a percentage in css. All these elements have a common class ‘display-class’

Eg.

input.test1 {
   width: 60%
}

Now in JS, I am trying to set a wrapper div to this element. I want the wrapper div to have the width of input field and set the width of input field to 100%

My current JS code looks like this –

document.querySelectorAll('.display-class').forEach((el) => {
    const wrap = document.createElement('div');
    wrap.classList.add('display-class-wrap');
    el.parentNode.insertBefore(wrap, el);
    wrap.appendChild(el);
    wrap.style.width = el.style.width;
    el.style.width = '100%';
});

When I try to log the width’s of both elements, it returns me empty string for length of input element.

I also tried setting the width by calculating the percentage myself like so,

wrap.style.width = `${(el.clientWidth/wrap.parentElement.clientWidth)*100}%`;

But it returns me width in float values that are way off the original width set. Eg. It returned 55.925% for 60%

2

Answers


  1. Use getComputedStyle to get the computed style for the input element

    document.querySelectorAll('.display-class').forEach((el) => {
        const wrap = document.createElement('div');
        wrap.classList.add('display-class-wrap');
        el.parentNode.insertBefore(wrap, el);
        wrap.appendChild(el);
        
        const computedStyle = window.getComputedStyle(el);
        wrap.style.width = computedStyle.width;    
        el.style.width = '100%';
    });
    
    Login or Signup to reply.
  2. You should use the .offsetWidth directly on the element. style will not return the width until the width is explicitly set on the element.

    But the gotcha around the offsetWidth is that it can return 0 if you do certain DOM modifications use setTimeout for those scenarios.

    Another option for you is to use getComputedStyle. Checkout the documentation on how to use it.

    If you can create a codeSandbox I can look into it as well :).
    I hope this helps

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search