HomeAbout

HTML and JS Linking

HTML and JS files are linked through a <script> tag's src attribute path.

<!DOCTYPE html> <html> <head> <title>Linking JS to HTML file</title> </head> <body> <h1>Header</h1> <button onclick="someFunction()"> Change H1 Text </button> <script src="script.js"></script> </body> </html>

The function defined in JS file is matched to a function defined in HTML file.

// script.js function someFunction() { let heading1 = document.querySelector('h1'); heading1.textContent = 'changed text content'; }

Another Example

<div class="container"> // <!-- function names parsed statically --> <button onclick="increment()"> Click Me! </button> <div class="counter"> <span class="counter-label">Times Clicked:</span> <span class="counter-value">0</span> </div> </div> function increment() { // class name referenced with "." prepend let val = document.querySelector(".counter-value").innerHTML; let newVal = new Number(val) + 1; // need to convert to number from string document.querySelector(".counter-value").innerHTML = newVal; // reselect and change value }
AboutContact