AngelOnFira AngelOnFira - 4 years ago 277
HTML Question

Can external JavaScript access DOM elements from a different file?

Just started working in Dreamweaver recently. I was wondering if when you are working with external javascript files, do you have to pass in html elements or can the js file see their id? For example;

<body>
<script src="client.js"></script>

<input type="submit" name="submit" id="submit" onclick="getValue()" value="Submit"></td>


And then in the client.js file

function getValue() {
"use strict";
document.getElementById(submit).value = document.getElementById(otherelement).value;
}


This isn't working in the first place and I understand that there are other errors, but mainly - can the client.js file see and use
getElementById(submit)
and
getElementById(otherelement)
?

Answer Source

I would suggest shying away from using inline JavaScript elements, and doing things differently. I'd suggest using addEventListener() to bind events from JavaScript.

So, remove the onclick attribute, and just do:

<input type="submit" name="submit" id="submit" value="Submit">

We will be adding the event in JavaScript. For this to work, the script needs to be ran after the page (DOM) is loaded. You can use window.onload = function(){} to do this or you can load the script at the end of the page (before </body>).

Anyway, in your JavaScript, you want to use:

document.getElementById("submit").addEventListener('click', function(event){
    // NOTE: You are clicking a submit button.  After this function runs,
    // then the form will be submitted.  If you want to *stop* that, you can
    // use the following:
    // event.preventDefault();

    // In here `this` will be the element that was clicked, the submit button
    this.value = document.getElementById('otherelement').value;
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download