Determining the width of an element in terms of percentage

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.

Answer №1

For accurate width measurements, it is best to directly access the .offsetWidth property of the element. The width may not be returned when accessing the style property until a width has been explicitly set on the element.

Keep in mind that offsetWidth may return 0 in certain cases where DOM modifications are made; consider using setTimeout for such scenarios. Alternatively, you can utilize getComputedStyle, following the necessary documentation for proper usage.

If you provide a codeSandbox link, I can further investigate the issue :). Hope this information proves helpful!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for storing unique values in an object using JavaScript

I need assistance with organizing my log data, which includes camera names and system IP addresses. I am trying to create an object where each unique system IP is a key, with an array of corresponding camera names as the value. Here is the code snippet I h ...

Issue with Bootstrap 3: Element refuses to remain within the defined width of the div container

While utilizing bootstrap 3 within a small div, I noticed that when I enlarge the window by dragging it horizontally, the fields (username and password input fields) that should remain inside the div end up shifting towards the center of the window. Can an ...

Exploring the Past: How the History API, Ajax Pages, and

I have a layout for my website that looks like this IMAGE I am experimenting with creating page transitions using ajax and the history API. CODE: history.pushState(null, null, "/members/" + dataLink + ".php" ); // update URL console. ...

Navigational assistance on the keyboard - Improving Accessibility

My situation involves selecting an option from a dropdown menu on X-page, which triggers the opening of Modal-1 while disabling the background. If a selection is made within Modal-1, it leads to Modal-2. I am facing two issues/questions: Upon opening Moda ...

Sinon's fakeTimers failing to trigger

I'm encountering an issue with sinon's fakeTimers while working in a setup that includes Marionette.js, underscore, and chai test runner. Strangely, when I place a breakpoint in Chrome and step through the code, my timer functions as expected. Ho ...

What is the process for getting involved with npm commands?

Here is an excerpt from my package.json file: "scripts": { "cpFile": cp ../template/index.js /src/view/home/ } When I try to run the command: npm run cpFile fileName.js I expect it to execute: cp ../template/index.js /src/view/home/fileName.js How ...

Vue project encountering issue with displayed image being bound

I am facing an issue with a component that is supposed to display an image: <template> <div> <img :src="image" /> </div> </template> <script> export default { name: 'MyComponent', ...

What steps are needed to switch colors after a loop has been clicked?

I have a loop setup like this: data: { show: false } .test { hight: 10px; background-color: red; } .test2 { hight: 15px; } <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div v-for="value in da ...

Rendering v-html in VueJS requires a delayed binding value that can only be triggered by clicking inside and outside of a textarea control

I'm currently experiencing an issue with a textarea that is bound to a v-model with a specific value. The problem arises when the content of the textarea is changed via JavaScript - the displayed value, represented by {{{value}}}, doesn't update ...

What is the process for updating the class of the target button?

I am new to using Vue and struggling to achieve a specific functionality. I have multiple buttons and I want to ensure that only one button can be selected at a time. Currently, I have tried implementing it with the following code: :class="isActive ? ...

Having trouble implementing the page object model with cucumber.js: bug detected!

I have been working on implementing a page object pattern in my cucumber.js test automation suite with selenium webdriver. However, I am facing an error when trying to call the page object from my test step. The folder structure I am using is as follows: ...

Sending a jsp page for review at specified intervals

Using the setTimeout method, I attempted to achieve this. I passed a variable containing time as an argument, but the setTimeout method is only taking the initialized value of that variable and not the updated value fetched from the database. Below is the ...

"Engaging with the touchscreen inhibits the triggering of click

Within this div, I have implemented touch-action:pan-y;. Surrounding this div is an anchor tag. If you click on the div, the link will successfully redirect. However, if you swipe on the div and then click, the link won't work on the first attempt bu ...

Difficulty in extracting data from child elements of JSON documents

Below is the JSON String: "book_types": { "type": "1", "books": [ { "name": "default", "cover": null, "lastUpdated": { "microsecond": 114250, "ctime": "Fri Aug 9 01:27:45 ...

utilizing geographical coordinates in a separate function

I have a program that enables users to access the locations of communication cabinets. I am attempting to utilize html5 to transmit latitude and longitude information to a php script (geo.php) in order to update the database record with map coordinates. Ho ...

Updating the scope variable in an AngularJS directive

Recently delving into Angular, I encountered an issue: I have both a list view and a details view with tags. To facilitate navigating between the two views and loading new elements from a service upon click events, I created a directive. My aim is to also ...

Unable to retrieve the URL using the getDownloadURL function from Firebase

I have been using Firebase storage to successfully store images, however I am encountering an issue when trying to retrieve the image URL from a promise. const imageSaveHandler = (e) => { e.preventDefault(); const uploadTask = storage.ref(`i ...

Is it possible to access JSON with a numeric key and receive undefined as a result?

I've been attempting to extract information from my JSON data, but I keep getting an undefined result. Here is a snippet of my JSON: { "1": "A", "2": "B", "3": "C", "4": "D", "5": "E", "6": "F", "key":"pair" } This i ...

Is it accurate to consider all JavaScript code and variables as inherent properties of an execution context?

It's worth considering that everything in JS code can be viewed as a property of an execution context, whether it's a global, function, or eval() execution context. Why is this the case? Each execution context has its own unique lexical and v ...

Why is the Material Ui code functioning flawlessly in Codepen but not in VSCODE?

In my ReactJS project, I am using Material-UI to create "Material Tabs". The code works fine in SANDBOX but not in my VS CODE. What could be the issue? I have checked that Node is installed and all dependencies versions from NPM are up to date. I also tri ...