Jakub M.
Jakub M.

Reputation: 33857

How to find the script tag's parent

How to find an element relative to script's position? For instance, in the case below I would like getSelfParent to return the $('button') element

<button>
    <script>
        getSelfParent().click(function(){...});
    </script>
</button>

$(this).parent() did not work.

EDIT:

I want to avoid:

Upvotes: 6

Views: 3527

Answers (3)

DiverseAndRemote.com
DiverseAndRemote.com

Reputation: 19888

you should do:

<button>
    <script type="text/javascript" id="myscriptToHide1">
        jQuery('#myscriptToHide1').parents('button').hide();
    </script>
</button>

Upvotes: 1

Andrew D.
Andrew D.

Reputation: 8220

@Jakub M: this is the way I want to create buttons in my php.

Try to generate HTML|SCRIPT output as:

<button>
    <script id='RandomOrUniqueIdValue'>
        var script=document.getElementById('RandomOrUniqueIdValue');
        // var script=$('#RandomOrUniqueIdValue');
    </script>
</button>

Upvotes: 5

clem
clem

Reputation: 3366

I don't think there's really a way of accessing the parent element of a script tag, as a script is executed in reference to the window object, not the html tag it is in.

generally speaking, rather than copying and pasting the same/similar piece of javascript inside each button element, it would make more sense to just give them a class and access them in a single js function

Upvotes: 1

Related Questions