Find the specific size of an HTML element

How can you retrieve an element's dimensions while avoiding CSS properties that take up unnecessary space?
For example:

<!DOCTYPE html>
<html>
<head>
    <style>
    #foo {
        height: 48px;
        margin: 64px;
        width: 120px;
        padding: 23px;
        border:  7px solid red;
    }
    </style>
</head>
<body bgcolor="#ffffff">

<input type="text" id="foo"/>

</body>
</html>

The computed style would appear as follows:

https://i.sstatic.net/id8pR.png

Methods I attempted:

1.) Using clientHeight and clientWidth

document.querySelector('#foo').clientHeight
94
document.querySelector('#foo').clientWidth
166

2.) Utilizing getClientRects and getBoundingClientRect

document.querySelector('#foo').getClientRects() // identical to getBoundingClientRect()
DOMRectList {0: DOMRect, length: 1}
0: DOMRect {x: 72, y: 72, width: 180, height: 108, top: 72, …}
length: 1
[[Prototype]]: DOMRectList

3.) Checking for width and height:

document.querySelector('#foo').width
0
document.querySelector('#foo').height
0
document.querySelector('#foo').style.height
""
document.querySelector('#foo').style.width
""

Expected results:

{'width: 120, height: 48}
{'element': {'width: 120, height: 48}, 'spacing': {'top': 64+7+23, 'left': 64+7+23 ...}  // perfect!

Answer №1

Wishing that this snippet of code proves useful to you.

const element = document.querySelector('#elementId');
window.getComputedStyle(element).margin; 
window.getComputedStyle(element).width;
window.getComputedStyle(element).padding; 
window.getComputedStyle(element).borderBlockEndWidth;

Answer №2

Currently, my focus has shifted towards exploring the properties of

window.getComputedStyle(el, null)
in order to pinpoint the relevant attributes.

let spacingAttrs = [
  'borderBottomWidth', 
  'borderTopWidth', 
  'borderRightWidth',
  'borderLeftWidth',
  /*
  'marginBottom',
  'marginLeft',
  'marginRight',
  'marginTop',
  */
  'paddingBottom',
  'paddingLeft',
  'paddingRight',
  'paddingTop',
]

let num = 0
let el = document.querySelector('#foo')
let rect = el.getClientRects()[0];
let style = window.getComputedStyle(el, null)
let numberPattern = new RegExp(/\d+/);
let spacing = {'left': 0, 'right': 0, 'top': 0, 'bottom': 0}

for (let attr of spacingAttrs) {
  if (attr in style) {
    num = 0;
    for (let [key, value] of Object.entries(spacing)) {
      if (attr.toLowerCase().includes(key)) {
        num = numberPattern.exec(style[attr]);
        if (num) {
          // assuming units are Pixels only!
          spacing[key] += parseInt(num)
        }
      }
    }
  }
}

result = {
  'rect': {
    'w': rect.width - spacing.left - spacing.right,
    'h': rect.height - spacing.top - spacing.bottom
  },
  'spacing': spacing
}

Output:

rect: {w: 120, h: 48}
spacing: {left: 30, right: 30, top: 30, bottom: 30}

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

The Dysfunction of JQuery UI 1.12.1 Autocomplete

I am encountering some challenges with implementing JQuery UI. The version of JQuery UI I am using is 1.12.1, the latest one available. I have downloaded the autocomplete feature along with all other necessary widgets. In my project, I have placed jquery ...

Adding an element to the second-to-last position in a list

In the context of a HTML unordered list <ul id = "master_key_list"> <li id="master_key_23" class="available_element">Fix the Peanut Butter</li> <li id="master_key_24" class="available_element">Focus on Price Sensitivity</li& ...

Using Typescript to automatically infer strongly-typed recursive index types

Commencing with an Animal interface and a detailed map of animals residing on my farm: export interface Animal { species: string; edible: boolean; } export interface FarmMap{ [key: string]: Animal; } Everything seems to be running smoothly. Here ...

run a function once ngFor has completed rendering the data

I'm attempting to run a function every time my ngFor finishes loading data from the API. However, the callback only works on the initial load of the ngFor. How can I make sure that the callback is executed whenever my ngFor data changes? I found a ...

The output from the Moment.js HTTP server is currently experiencing errors and is not displaying the expected

My first time working with JavaScript and the Momentjs library has not been smooth sailing. I am facing an issue where the output is not displaying as required. The goal is to show dates in the format "Day, date month year" (e.g., Tuesday, 14th May 2018). ...

When the mouse is clicked, rotate the object along its axis using OBJ Loader in THREE.js

I am looking to add a feature where my object rotates on its axis when the mouse is dragged. The challenge I am facing is that I can only access my skull object within the function, which limits where I can place a rotation increment inside render(). Coul ...

In order to ensure that the multiselect bootstrap dropdown options drop outside of the div and prevent scroll bubbling, there are specific

I am trying to customize a bootstrap multiselect dropdown located within a div. You can find an example of what I'm working on at this link: http://jsfiddle.net/The_Outsider/8watL2L1/9/ In my design, I want the multiselect dropdown options to drop ou ...

Struggling to eliminate buttons upon clicking, but they persistently reappear (JavaScript, HTML)

I have encountered an issue with buttons in my table that I am struggling to resolve. Each row in the table contains a "Pack" action button, which when clicked, is removed to prevent accidental double-packing of items. Everything was functioning smoothly ...

Choose the key value from a deep object structure

I'm facing a dilemma. Within the layers of this object, I need to identify and select a specific key among the nested elements. The structure of the object is as follows: var x={ "_shards": { "total": 10, "successful": 5, ...

JQuery plugin for creating interactive date selection forms

Having some trouble creating a dynamic form. The datepicker seems to only work on the first row and I can't click it. Tried a few different codes but no luck so far. Below is the code excluding the PHP part, which is just for inserting into a database ...

Designing a website similar to sevenly.org using jquery: A step-by-step guide

My understanding of javascript and jquery is at a beginner level. I am interested in creating a design similar to Sevenly, where one page/div moves over another. I'm not sure where to begin with this. Any advice or ideas on how to implement this effec ...

Enter the quiz that starts counting down as soon as you open it

Is there a way to develop a web application that can send emails to specific users with a link that expires in 3 days? When the user clicks on the link before it expires, a new browser window/tab will open with personalized questions and a countdown timer ...

JavaScript array loading failed for the C# web service

I am encountering an issue with a JavaScript object in my application that contains an array object, which is a collection of objects with two properties (Name, Value) on the server-side. Despite my efforts, when the code reaches the C# web service, the C ...

Tips on setting the default sorting order in AngularJS

I have implemented a custom order function in my controller with the following code: $scope.customOrder = function (item) { var empStatus = item.empState; switch (empStatus) { case 'Working': return 1; case & ...

I am having trouble locating my TypeScript package that was downloaded from the NPM registry. It seems to be showing as "module not found"

Having some challenges with packaging my TypeScript project that is available on the npm registry. As a newcomer to module packaging for others, it's possible I've made an error somewhere. The following sections in the package.json appear to be ...

There seems to be a problem with playing a UI video, but interestingly it functions

I am facing an issue with playing MP4 (HD) videos on the UI that I receive from the Django backend. My setup involves using normal Javascript on the frontend and Django on the backend. Here is a snippet of the backend code: file = FileWrapper(open(path, &a ...

Sliding Toggle: Panel Revealed with Button Slide

Currently, I am working on implementing a jquery slide tab feature. The functionality is working fine on button click. However, I want the button to stick with the panel and slide along with it. At the moment, the button remains fixed while the panel slide ...

In JavaScript, it is not possible to retrieve the maximum or minimum value of an array

Hey there! I'm having some trouble finding the minimum and maximum values in an array. Can you help me figure out what's going on with my code? var repeated, studentsArray = [], marksArray = []; while (repeated !== 'n' && r ...

Angular does not alter the focus when a new component is loaded

Currently, I am working on resolving an accessibility issue with a screen reader in an Angular2 web application. When componentA (code shown below as Before) is loaded in Chrome, the entire browser window gains focus and the screen reader narrator announce ...

A step-by-step guide on transforming an array of objects into an array of arrays with the help of Ramda

I want to convert the following data: [ { a: 2000, b: 4000 }, { a: 8000, b: 5000 }, { a: 6000, b: 1000 } ]; Into this format: [ [ 2000, 8000, 6000 ], [ 4000, 5000, 1000 ] ]; Using Ramda library. I am able to achieve this using R.reduce functio ...