-1

I want to set an attribute of "attribute" with the value of "value" on the Sprint link, why is the parentElement returning undefined?

<a> Sprint
    <script>  
      const value = "sprint-info"
      const target = this.parentElement;
      target.setAttribute("attribute", "value");
      console.log(target)
    </script>  
  </a>
EliasSDA
  • 17
  • 1
  • 6

3 Answers3

0

Try:

<a> Sprint
    <script>  
      const value = "sprint-info"
      const target = document.currentScript.parentElement;
      target.setAttribute("attribute", "value");
      console.log(target)
    </script>  
  </a>
David Callanan
  • 5,601
  • 7
  • 63
  • 105
0

You can add an id to the script tag, and get the parentElement using querySelector.

<a> Sprint
    <script id="myScript">  
      const value = "sprint-info"
      const target = document.querySelector("#myScript").parentElement;
      target.setAttribute("attribute", "value");
      console.log(target)
    </script>  
  </a>
TechySharnav
  • 4,869
  • 2
  • 11
  • 29
-1

A script tag is not treated as a tradition DOM element, you're better of just using a querySelector

<a class="sprint"> Sprint </a>

<script>  
      const value = "sprint-info"
      const target = document.querySelector('.sprint');
      target.setAttribute("attribute", "value");
      console.log(target)
</script>  
  • This solution does work, but does not directly answer the question. Also I believe the statement "A script tag is not treated as an HTML element" is incorrect. – David Callanan Jul 31 '21 at 14:53
  • 1
    A script tag is most definitely treated as an HTML element. An [`HTMLScriptElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement) to be precise. – Ivar Jul 31 '21 at 14:55
  • Sorry I guess I should have said "tradition DOM element" my bad, reading that again I can understand that could have caused confusion – Mamunur Qureshi Aug 02 '21 at 11:10