0

From inside a javascript file, how can we detect the parent of this script tag without any id and class by jquery.

(function() {
    $(this).parent('div').attr('id');
})();
matsjoyce
  • 5,744
  • 6
  • 31
  • 38

2 Answers2

1

You can do it like this:

<div class="parent">
    <script>
        var scriptTags = document.getElementsByTagName('script');
        var parentTag = scriptTags[scriptTags.length-1].parentNode;
        alert(parentTag.className);
    </script>
</div>

Note that you have to get the script tags at once and not on DOM ready.

Tetaxa
  • 4,375
  • 1
  • 19
  • 25
0

In one line jQuery: var script = jQuery('script').last().parent();

Note:

Do NOT cast this in ready event, because then the last script might not be the script you are searching for.
Mephiztopheles
  • 2,228
  • 1
  • 12
  • 25