My issue involves input elements with widths set as percentages in CSS under the common class 'display-class'
For example:
input.test1 {
width: 60%
}
In JavaScript, I am attempting to wrap a div around these input fields with the same width and set the input field width to 100%
The current JS code snippet 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%';
});
However, when checking the widths of both elements, it returns an empty string for the input element's length.
I also attempted to calculate the percentage manually like so,
wrap.style.width = `${(el.clientWidth/wrap.parentElement.clientWidth)*100}%`;
But the result was float values significantly off from the original width set. For instance, it returned 55.925% instead of 60%
Snippet:
// JavaScript functions included here
// HTML and CSS styling included here
The answer provided did not resolve my doubt. I need the precise percentage value set in CSS, as getComputedStyle()
only returns values in pixels, leading to inaccurate manual calculations.