-2

If the size of an element, say for this case - a body element, is not known or it can be mentioned in any of the mentioned formats mentioned here: https://developer.mozilla.org/en-US/docs/Web/CSS/width, is it possible to get the size of the containing element for that element?

For example:

<html>
<head>
    <link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
  <section>
    <p id="test">This is a paragraph!</p>
  </section>
</body>
</html>

Here say size of body is set to 50% or 300px, how can I get the size of the whole document? Apologize if this is stupid, new to this side of things. This is not a duplicate of How to find the width of a div using vanilla JavaScript?, because I am asking for the width of a container element and not the element itself.

ssn
  • 2,631
  • 4
  • 24
  • 28
  • 1
    Possible duplicate of [How to find the width of a div using vanilla JavaScript?](https://stackoverflow.com/questions/4787527/how-to-find-the-width-of-a-div-using-vanilla-javascript) – MyLibary Nov 06 '19 at 21:25
  • You could try to traverse up one parent node with [Node.parentNode](https://developer.mozilla.org/en-US/docs/Web/API/Node/parentNode) in your JS – Andrew Nov 06 '19 at 21:25
  • 1
    @MyLibary Really isn't a duplicate even if it's similar. – Andrew Nov 06 '19 at 21:28
  • Yes, I don't believe this is a duplicate, since the question is about the container element and not the element itself. – ssn Nov 06 '19 at 21:38

1 Answers1

2

You can use the parentNode property to find the parent of an element. You can then use the offsetWidth and offsetHeight properties to find the width/height of the element.

var parentElem = document.getElementById('test').parentNode;
var parentWidth = parentElem.offsetWidth;
var parentHeight = parentElem.offsetHeight;
MEnf
  • 1,482
  • 1
  • 12
  • 18