Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain a reference to <script> parent element [duplicate]

I have a similar problem like posted here but instead of obtain the parent id, how Can I get a reference to the script parent without having to code an id for the script tag?

For example, I have the following code injected to a website:

<div>      some other html tags      <script src="http://path_to_my_script.js"></script> </div> 

What I need is that in my path_to_my_script.js file I can get a reference to the outer div.

There is a catch and is that the code will be copied&pasted in several places in the same webpage, which makes an identifier useless.

There is any chance to do that without to code an id in the entire code?

If the solution is with jQuery the better :D

Thanks in advance.

like image 447
Diosney Avatar asked Apr 24 '12 14:04

Diosney


People also ask

How may I reference the script tag that loaded the currently executing script?

Use document. document. currentScript will return the <script> element whose script is currently being processed.

What is parentNode parentNode In JavaScript?

parentNode. The read-only parentNode property of the Node interface returns the parent of the specified node in the DOM tree. Document and DocumentFragment nodes can never have a parent, so parentNode will always return null .

What is use of defer In script tag?

The defer attribute is a boolean attribute. If the defer attribute is set, it specifies that the script is downloaded in parallel to parsing the page, and executed after the page has finished parsing.

What does defer do In HTML?

defer. This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded . Scripts with the defer attribute will prevent the DOMContentLoaded event from firing until the script has loaded and finished evaluating.


1 Answers

As mentioned in What is the current element in Javascript?, the current <script> element is also the last <script> element, at the time of execution.

The answer also applies to your case, since the load of the external script is not deferred (through the async or defer attribute).

var scriptTag = document.getElementsByTagName('script'); scriptTag = scriptTag[scriptTag.length - 1]; var parentTag = scriptTag.parentNode; 

Most browsers (even IE6) support document.scripts. Firefox supports this object as of version 9. So, the following code can also be used:

var scriptTag = document.scripts[document.scripts.length - 1]; var parentTag = scriptTag.parentNode; 
like image 192
Rob W Avatar answered Sep 20 '22 11:09

Rob W