-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.

4
  • 1
    Possible duplicate of How to find the width of a div using vanilla JavaScript? Commented Nov 6, 2019 at 21:25
  • You could try to traverse up one parent node with Node.parentNode in your JS Commented Nov 6, 2019 at 21:25
  • 1
    @MyLibary Really isn't a duplicate even if it's similar. Commented Nov 6, 2019 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. Commented Nov 6, 2019 at 21:38

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.