nothrow
nothrow

Reputation: 16178

Access element, which contains current <script>

I've got following page:

<div><script>AddSomeContent(??, 1)</script></div>
<div><script>AddSomeContent(??, 2)</script></div>

I need to replace the ?? with the surrounding <div> DOM object, so the function AddSomeContent can modify it. Is there any oportunity to do this?

Before any other comments: I don't have any other option. I'm already trying to hack some existing page, and only thing I can control is content of the <script>.

I'm using jquery, but I can change it.

Edit: for clarification. AddSomeContent looks like:

function AddSomeContent(somediv, parameter)
{
     $(somediv).append('there goes some data, that I dynamically create from some stuff depending on the parameter');
}

And I want to first div contain result with parameter = 1, second div parameter=2

Upvotes: 1

Views: 117

Answers (2)

Phil H
Phil H

Reputation: 20151

I remember this from a previous question. The number of scripts on the page is incremented by 1 with each script that is processed, and they are processed in order. So this function will get the current script number:

function countScripts() {
    return document.scripts.length;
}

Then you can go get the parentNode of that script:

var thisScriptParent = document.scripts[countScripts()].parentNode;

Upvotes: 1

Pointy
Pointy

Reputation: 413826

You can try this, though it's somewhat of a hack:

(function() {
  var scr = document.getElementsByTagName('script'),
      parent = scr[scr.length - 1].parentNode;
  // parent is the parent node of the last script on the page
})();

If you've got code in <script> tags like that, then when it runs the last script on the page will be the one that contained it.

Upvotes: 4

Related Questions