Hamed Minaee
Hamed Minaee

Reputation: 2560

I cannot get the accurate height of an element with pure javascript

I use the following function to get the full height of an element:

outerHeight1=(el)=> {
    let style = window.getComputedStyle(el);

    return (parseInt(style.getPropertyValue("height").replace("px",""))+
        parseInt(style.getPropertyValue("border-bottom-width").replace("px",""), 10)+
        parseInt(style.getPropertyValue("border-top-width").replace("px",""), 10)
    );
}

It is noteworthy that the elements are added dynamically to the dom. What I see is the rendered height that I checked in chrome is about 3 px more than what my function returns so the rendered dom returns 55 but my function returns 52.

Any idea?

Update:

as suggested I used getBoundingClientRect and I get 0 for height. Here is the log in my console

enter image description here

Upvotes: 0

Views: 847

Answers (2)

PopHip
PopHip

Reputation: 768

Why don't you use element.offsetHeight ? It would return element's height including padding and border

Upvotes: 0

DSCH
DSCH

Reputation: 2366

You can use element.getBoundingClientRect() it shall return an object where one of its keys is height. You can read the docs here

Upvotes: 3

Related Questions