Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • adding ID's anywhere
  • traversing whole tree every time I am looking for the self element
like image 894
Jakub M. Avatar asked Sep 13 '11 10:09

Jakub M.


People also ask

Where does the script tag belong to?

The <script> Tag Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.

What is JavaScript parent?

The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.

Can I have 2 script tags?

Up to this point all of the JavaScript Code was in one <SCRIPT> tag, this does not need to be the case. You can have as many <SCRIPT></SCRIPT> tags as you would like in a document. The <SCRIPT> tags are processed as they are encountered.


2 Answers

@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>
like image 165
Andrew D. Avatar answered Oct 28 '22 16:10

Andrew D.


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

like image 2
clem Avatar answered Oct 28 '22 15:10

clem