Alvin
Alvin

Reputation: 265

How do I access a dynamically loaded element in jquery or javascript?

Okay here is the scenerio that is bugging me. I need to get the list of all elements within a dom, even the once that are dynamically loaded.

So say for instance a script element is created with

var script=document.createElement('script');
script.type='text/javascript';
script.src='somejsfile.js';
    $("head").append(script);

and if I do following that:

var doc = document.documentElement;
var scripts = doc.getElementsByTagName("script");
for (var idx in scripts)
{
    var s = scripts[idx];
    if (!s.src) continue;
    s = s.src;
    alert(s);
}

How come I don't see the dynamically added script? I tried it in Jquery with the same results.

Does anyone know how this can be achieved? perhaps with dom refreshing?

*Just to be clear: All I want is to loop through the dom and find the 'src' attributes of the 'script' elements, even the one that are dynamically loaded.

Upvotes: 1

Views: 1304

Answers (4)

Jeff Martin
Jeff Martin

Reputation: 11022

You are appending it with jquery, why not look for it with jQuery?

var scripts = $('script')

or even

var scripts = $('script[src]')

Upvotes: 0

Geomisk
Geomisk

Reputation: 1

It looks like NeXXeuS is correct. You can also append the your new element without jQuery:

var newNode = document.createElement("script");
newNode.type = "text/javascript";
newNode.src = "somescript.js";
document.body.appendChild(newNode);

Try running it inside the JavaScript console in Firefox or Chrome and you will see the new script get added appended to the body tag in this case.

Upvotes: 0

mVChr
mVChr

Reputation: 50177

You need to append the dynamically created script to the DOM somehow first. Here's a foolproof way:

var ref=document.getElementsByTagName('script')[0],
    script=document.createElement('script');
script.type='text/javascript';
script.src='somejsfile.js';
ref.parentNode.insertBefore(script, ref);

Upvotes: 1

mattsven
mattsven

Reputation: 23253

Did you add it to the dom...?

var script=document.createElement('script');
script.type='text/javascript';
script.src='somejsfile.js';

$(script).appendTo("head"); //or body

Upvotes: 3

Related Questions