I have the following code:
<div>
<script>
// get the width of the parent element
</script>
</div>
it is possibile to get the width (and the height) of the parent element where the script tag is placed?
I have the following code:
<div>
<script>
// get the width of the parent element
</script>
</div>
it is possibile to get the width (and the height) of the parent element where the script tag is placed?
Important note: the following solution is not supported in IE.
Yes, you can use document.currentScript
to get a reference to the current script tag, and then use parentNode
:
<div>
<script>
const {width, height} = getComputedStyle(document.currentScript.parentNode);
console.log({width, height});
</script>
</div>
document.getElementsByTagName("div").getBoundingClientRect().width
document.getElementsByTagName("div").getBoundingClientRect().height
Try currentScript.closest
<div>
<h1>Content</h1>
<script>
const thisScript = document.currentScript;
const container = thisScript.closest("div")
const ch = container.clientHeight;
const oh = container.offsetHeight;
const sh = container.scrollHeight;
const h = container.style.height || "not set";
const gc = getComputedStyle(container)
console.log(ch, oh, sh, h, gc.height)
</script>
</div>