Dr.Knowitall
Dr.Knowitall

Reputation: 10468

How can I access DOM objects in an external JavaScript file?

I'm using an external JavaScript file to access DOM objects with in my documents. The problem is that jQuery doesn't seem to have access if it's an externally loaded file. My code looks like:

<html>
    <head>
    </head>

    <body>
        <div id="domToChange" someAttribute="hi"></div>
        <script src="officialJqueryLibrary"></script>
        <script src="myJS.js"></script>
    </body>
</html>

///////// myJS.js file

// Returns undefined
$('#domToChange').attr('someAttribute');

The DOM selector doesn't seem to find my div when the JavaScript file is loaded externally. However everything works when I place it inside the HTML document itself. How can I give DOM access to my JavaScript file?

Upvotes: 1

Views: 6222

Answers (4)

Michiel Dral
Michiel Dral

Reputation: 4067

You should wrap all your DOM related code into

$(function() {
    //Code
});

Then the code gets executed when the DOM is fully loaded.

Upvotes: 1

RicardoE
RicardoE

Reputation: 1725

You have to enclose the code like this:

$(function(){
     $('#domToChange').attr('someAttribute');
});

So that the code is executed when the DOM is ready.

Upvotes: 0

woofmeow
woofmeow

Reputation: 2408

OK, this is a hit and miss kind of thing (but I believe it be an accurate explanation), but the real explanation for why it is happening lies here.

You need to understand that jQuery is an object that is initialized. So the jQuery object takes time to initiatize. As it says,

is very important to make the distinction between jQuery object and native DOM elements. Native DOM methods and properties are not present on the jQuery object, and vice versa.

So it is not necessary that the jQuery object gets initialized at the same time the DOM gets initialized.

Also, all scripts that are passed have a defer attribute. This is mostly browser dependent.

As it says,

When set, this boolean attribute provides a hint to the user agent that the script is not going to generate any document content (e.g., no "document.write" in javascript) and thus, the user agent can continue parsing and rendering.

And it can sometimes delay the execution of the script. Hence the different result according to different people.

Upvotes: 0

Nicolae Olariu
Nicolae Olariu

Reputation: 2555

Try getting the value for your attribute, like so:

$('#domToChange').attr('someattribute');
//or
$('#domToChange').attr('someAttribute'); // i know you've tried this, but pls check demo

Demo here. On my machine, browser Chrome Version 28.0.1500.95 m, it just works fine.

Upvotes: 0

Related Questions