0

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?

ipel
  • 1,326
  • 1
  • 18
  • 43
  • 2
    Does this answer your question? [How may I reference the script tag that loaded the currently-executing script?](https://stackoverflow.com/questions/403967/how-may-i-reference-the-script-tag-that-loaded-the-currently-executing-script) – Mohamed Mufeed Dec 17 '20 at 18:32

3 Answers3

4

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>
blex
  • 24,941
  • 5
  • 39
  • 72
0
document.getElementsByTagName("div").getBoundingClientRect().width
document.getElementsByTagName("div").getBoundingClientRect().height
Waleed Khalid
  • 86
  • 1
  • 5
0

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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236