guradio
guradio

Reputation: 15555

getting width of an element in JS not getting expected result for width

$(parentelement).find(".spec-table__thead.spec-table__thead--original th p").each((function(index, element) {
  console.log($(element))
  console.log($(element)[0].clientWidth)
  i.push($(element)[0].clientWidth)
}));

I have the code above and the console returns:

enter image description here

But upon checking the inside of the $(element)

I can see :

className: ""
clientHeight: 47
clientLeft: 0
clientTop: 0
clientWidth: 585
contentEditable: "inherit"

meaning value that I should be getting is 585 but why do I get 696

FYI: using the first entry as sample.

Upvotes: 1

Views: 188

Answers (4)

guradio
guradio

Reputation: 15555

It turns out css is adding padding on the width

Upvotes: 0

h34dsp1nns
h34dsp1nns

Reputation: 82

My guess is that you are inspecting a different element than you are logging - maybe a padded container element. clientWidth should give you the width of the element.

You could double check against the boundingRect, but the values will surely be the same.

let boundingrect = element.getBoundingClientRect();
let clientWidth = element.clientWidth;
let boundingWidth = boundingrect.width;
let testWidth = boundingrect.right - boundingrect.left;
console.log(`client: ${clientWidth}, boundingwidth:${boundingWidth}, testWidth: ${testWidth}`);

Upvotes: 0

Wajid
Wajid

Reputation: 593

First you need to check which index have clientWidth. Because your response is not complete so I can't tell you which index have valid value. Check index like maybe it is on index 1 or any other

$(parentelement).find(".spec-table__thead.spec-table__thead--original th p").each((function(index, element) {
  console.log($(element))
  console.log($(element)[1].clientWidth)
  i.push($(element)[1].clientWidth)
}));

Upvotes: 1

Irfan wani
Irfan wani

Reputation: 5065

Actually this is not any error. It just changes because the console decreases the width of the viewable area. If you shift your console to the bottom, you will see that the results will be same.

Note that the clientWidth which you console logged is the right one, i.e, that is the width of the viewable portion of the element when the console is not open and the clientWidth present in the element which you console logged as whole is the viewable width when the console is open. That is why it is less than the first one.

Upvotes: 1

Related Questions