How to define the parent element



  • There is a need for Javascript (crossbrew) to define the parent element - container for the current <script src="script.js"></script> (from the violin itself - script.js) Given that such designs <div class="container">...</div> Maybe a few, and each needs to be determined. container

    <div class="container">
        <script type="text/javascript">
            var onViewable = function (result) {
                if (result) {
    
            }
        }
    &lt;/script&gt;
    &lt;script src="script.js"&gt;&lt;/script&gt;
    

    </div>



  • There is such a characteristic. https://developer.mozilla.org/en-US/docs/Web/API/Document/currentScript but it's not everywhere. Accordingly, finding a parent is simply:

    var parentElement = document.currentScript.parentNode;
    

    Got another one. http://www.2ality.com/2014/05/current-script.html works in all browsers if you don't dynamically add elements. <script>

    var parentElement = document.scripts[document.scripts.length - 1].parentNode;
    

    Example:

     <div>Test script 1
     <script>
      document.currentScript.parentNode.style.border = '1px solid blue';
     </script>
     </div>
     <div>Test script 2
     <script>
      document.scripts[document.scripts.length - 1].parentNode.style.border = '1px solid red';
     </script>
     </div>
     <div>Test script 3
     <script>
      document.scripts[document.scripts.length - 1].parentNode.style.border = '1px solid green';
     </script>
     </div>
     <div>Test script 4
     <script>
      document.currentScript.parentNode.style.border = '1px solid green';
     </script>
     </div>

    First and last <div> IE will not be within the framework.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2