简体   繁体   中英

How do I use document.getElementById() in a separate js file?

Learning how to do webdev for the first time, and to make things neater, I'm storing my scripts in their own files. I've been trying to figure out how to access elements from this separate file but I cannot figure out how.

This is the relevant bit of the JS file

function getSelectedText() {
        if document.getElementById("card1").checked == true {
            //code here
        }
}

This is the relevant HTML it's trying to access

<script type="text/javascript" src="js/cards.js"></script>
<input id="card1" type="radio" name="card" value="1" checked>Test1<br>
<input id="card2" type="radio" name="card" value="2">Test2<br>
<input id="card3" type="radio" name="card" value="3">Test3<br>
<button onclick="updateCard()">View card</button>

I want to access and edit the radio inputs but the JavaScript file throws an error when I try to reference document. Is there any way to reference the HTML file or do I need to use a different method/shove the code into the html?

Firstly, it should be:

if (document.getElementById("card1").checked)

You forgot the pair of bracket. As for getting the JavaScript code to work, you'll need a <script src="your js file"></script> element in your HTML file, and the code should work just all right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM