1

Is possible to getting parent element from the location of the called function?

my case:

<div class="alphabet">
    <div class="lorem">
      <script type="text/javascript">
        getParent();
      </script>
    </div>

    <div class="ipsum">
      <script type="text/javascript">
        getParent();
      </script>
    </div>

    <div class="dolor">
      <div class="amet">
        <script type="text/javascript">
          getParent();
        </script>
      </div>

    </div>
  </div>
<script>
function getParent(){

  //......????????.......//

}
</script>

Expected Result (Console Log):

  1. getParent() > the parent is lorem
  2. getParent() > the parent is ipsum
  3. getParent() > the parent is amet
Abu Ayyub
  • 401
  • 4
  • 14
  • Possible duplicate of [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) – apple apple Apr 27 '18 at 02:32
  • no... its different question – Abu Ayyub Apr 27 '18 at 02:38
  • @AbuAyyub actually if it really is a different question, then my answer below is wrong o.O But then can you explain? – konrados Apr 27 '18 at 02:48
  • ok, i get that point, the main solution is "document.currentScript"... sorry for my mistake, still newbie :) – Abu Ayyub Apr 27 '18 at 02:58

1 Answers1

2

This should work, although my intuition tells me you're doing something wrong.

<script>
    function getParent(){
        var me = document.currentScript;
        var parent = me.parentElement;
        console.log(parent.className);
        return parent;
    }
</script>
<div class="lorem">
  <script type="text/javascript">
    getParent();
  </script>
</div>

<div class="ipsum">
  <script type="text/javascript">
    getParent();
  </script>
</div>

https://jsfiddle.net/8tjsa8fw/

konrados
  • 1,047
  • 8
  • 21
  • Sure:) But again - you're doing something wrong. Why not make a script below your html and then reference the divs with e.g.document.querySelectorAll('.someClass').forEach(element){...}; i.e. like this is normally done? :) BBL – konrados Apr 27 '18 at 03:02
  • because i need the current parent of the function called when i load some page from ajax. – Abu Ayyub Apr 27 '18 at 03:13
  • and i put the script before

    not in

    , so that it is ran after all the elements have been rendered.

    – Abu Ayyub Apr 27 '18 at 03:17