Get width in pixels

Asked

Viewed 76 times

3

2 answers

5

You can use the .getBoundingClientRect() which returns an object with the dimensions of the element.

In your example it would be:

{
    height: 50,
    width: 813,
    left: 8,
    bottom: 58,
    right: 821,
    top: 8
}

Example:

var el = document.getElementById('rect');
var width_plan = el.getBoundingClientRect().width
alert(width_plan);  // 821

jsFiddle: http://jsfiddle.net/hxen50jq/

4


The secret is the getBoundingClientRect(). It returns the desired information for some time. It works on all browsers that are not very old.

document.body.innerHTML += document.getElementById('rect').getBoundingClientRect().width;
<svg width=100% height=100%>
    <rect id=rect rx=0 ry=0 x=0 y=0 width=100% height=50px fill=HoneyDew />
</svg>

I put in the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.