HTML (HyperText Markup Language) defines the structure and content of a webpage, while CSS (Cascading Style Sheets) controls its appearance. However, HTML and CSS on their own do not provide general-purpose programming functionality required to dynamically manipulate the document and implement complex behavior, which is where JavaScript comes in. Almost every modern, interactive webpage uses some form of scripting, and JavaScript is by far the most popular language for this purpose. JavaScript allows you to manipulate and make interactive webpages by altering the DOM (Document Object Model), which I will explain very soon.
Linking JavaScript to the Webpage
In this article, we will cover two ways to link JavaScript to an HTML document.
The first way, and the most widely used, is to link an external JavaScript file in the HTML file using the script tag. You can set the file's path in the src attribute. Here is an example:
<script src="scripts/index.js"></script>
If you want to wait until the HTML document has been parsed, you should add the defer attribute to your script tag. This is very useful when placing scripts in the head of your document, as it prevents them from blocking HTML parsing. Keep in mind, this only applies to external classic scripts. Module scripts are deferred by default. Here is how it would look:
<script src="scripts/index.js" defer></script>
The second way is to just write the code inside the script tags, as follows:
<script>
console.log("This is called inline JavaScript")
</script>
You can place script tags both in the head and body of your HTML document. Consider using the defer attribute if it is in the head. You can also place the script near the bottom of the body, so the HTML elements it needs will have already been parsed.
The Document Object Model
The Document Object Model represents a document in a tree structure, with each node representing an object corresponding to a part of the document. In the case of an HTML document, this tree represents the webpage and its elements.
This is important for building interactive web pages because it allows JavaScript to create, remove, access, and modify elements in the document. JavaScript can also use the DOM to attach functions to event handlers, which lets actions like button presses or text input trigger code execution.
Here is an example of how HTML corresponds to a DOM:
HTML
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>Document Object Model Example</title>
</head>
<body>
<section>
<img
src="test.png"
alt="Alternate text for this image" />
<p>
This is a link:
<a href="https://dev.to/tyleruploads/">Tyleruploads on DEV.to</a>
</p>
</section>
</body>
</html>


Selecting and Storing Elements as Variables
You can select elements from the document in many ways, then store them as variables. I will give some examples of common ways to select elements in JavaScript in this section.
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>Document Object Model Example</title>
</head>
<body>
<h1>Fruits List</h1>
<ul>
<li id="li-apple" class="fruit">Apple</li>
<li class="fruit">Banana</li>
<li class="fruit">Orange</li>
</ul>
</body>
</html>
If you want to store the list element that shows the text "Apple" as a variable, here are some ways to do it.
The getElementById() method allows us to select an element by its ID. If there is no element with the specified ID, it returns null.
const element = document.getElementById("li-apple");
The querySelector() method allows us to select an element by its CSS selector. The CSS selector for a class is .className, and the CSS selector for an ID is #id. The querySelector() method only returns the first element that matches the provided selector. If many elements match, only the first one is returned. If no elements match, it returns null.
const elementRef1 = document.querySelector("#li-apple");
const elementRef2 = document.querySelector(".fruit");
If you wanted to store a reference to all of the fruits, you can use the querySelectorAll() method. It returns a static NodeList, which contains every element that matches the CSS selector, not just one. If you passed it "li", you'd get the same result, since all the <li> elements have the fruit class. Unlike an HTMLCollection, a static NodeList does not automatically update whenever the document changes.
const fruits = document.querySelectorAll(".fruit");
Traversing the HTML DOM
Now that you know how to select elements, let's go a bit more into traversing the DOM. We will be using the same HTML as above, provided again for your convenience.
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>Document Object Model Example</title>
</head>
<body>
<h1>Fruits List</h1>
<ul>
<li id="li-apple" class="fruit">Apple</li>
<li class="fruit">Banana</li>
<li class="fruit">Orange</li>
</ul>
</body>
</html>
Let's say you want to iterate over each list item in the unordered list and print the content of every item to the console. To do this, you need to first get a reference to the unordered list, then iterate over its children. We will iterate over its children using the children property, which returns an HTMLCollection that contains the element's child elements.
const fruitUl = document.querySelector("ul");
for (const child of fruitUl.children) {
console.log(child.textContent);
}
The JavaScript will output:
Apple
Banana
Orange
If you want to select the parent of an element, you do so with the parentElement property. If the parent node is not an element, or the element has no parent, this property returns null.
const appleLi = document.getElementById("li-apple");
const appleUl = appleLi.parentElement;
Manipulating Properties and Styles of Elements with Dot Notation
Let's say you have selected an element el representing a <p> element, and would like to change its text to say 'altered'. You would use dot notation and 'textContent' to do this. Here is an example:
el.textContent = "Altered";
You could also save its current text to a variable, like as follows:
const text = el.textContent;
With this notation, you can change many things about an element. Here are some properties you can change, corresponding to what they represent:
| Property | Represents |
|---|---|
| innerHTML | The HTML contained inside the element |
| outerHTML | The HTML fragment describing the element, including its own opening and closing tags |
| textContent | The raw text content inside the element and all of its descendants, which includes invisible text |
| innerText | The rendered text content of the element and its descendants, taking visibility into account |
| tagName (READ ONLY) | The element's HTML tag in uppercase, like DIV or H6
|
| id | The id of the element |
Be careful when assigning user-provided or external data to
innerHTML, as it can introduce cross-site scripting (XSS) vulnerabilities. If you only need to change text, usetextContentinstead.
Modifying styles is very similar. Here are a few basic examples:
el.style.backgroundColor = "red";
el.style.borderRadius = "10px";
el.style.width = "80px";
el.style.fontSize = "3rem";
Keep in mind that the style property only accesses an element's inline styles. It doesn't directly modify the internal or external stylesheets themselves.
If you want a full list of properties, consult the w3schools HTML DOM Style Object List.
When manipulating CSS, it may be important to alter element classes, as shown below:
el.classList.add("primary-card");
el.classList.remove("primary-card");
el.classList.toggle("primary-card");
Working With Event Listeners
Event listeners allow us to execute functions in response to events, such as mouse clicks, keyboard input, or changes to an element. We can register these listeners using the addEventListener method.
The event that triggers when the HTML document has been fully parsed and the deferred and module scripts have been executed is called DOMContentLoaded. Keep in mind, this does not mean that all external resources, like images, have finished loading. If you want to link a function named loadedFunc to this event, you can do so as follows:
Make sure not to include parentheses after the function here! If you did, you would be calling a function immediately, as opposed to passing a function reference.
document.addEventListener("DOMContentLoaded", loadedFunc);
You can also attach to specific events on elements. To attach a function named clickedFunc() to the event handler for clicking on a specific element named el, you can use the following code.
el.addEventListener("click", clickedFunc);
If you want to define a function inside the addEventListener() method, you can use something called an arrow function, as shown below. Arrow functions are JavaScript's syntax for writing function expressions, which is commonly associated with lambda functions in other programming languages. The event variable in the parentheses represents the click event.
el.addEventListener("click", (event) => {
alert("Button Clicked. Deleting Button");
event.currentTarget.remove();
});
Creating, Appending, and Removing Nodes
To create a node, use the document.createElement() method, and pass the tag name of the element you want to create.
To insert a newly created element into the DOM, use the element.appendChild() method on the element intended to be the parent and pass a reference to the new child element. If it already exists somewhere in the document, it will be moved, rather than copied.
If you have references to the parent and child elements, you can remove a child element from the parent using the element.removeChild() method and pass the child element. The child must be a direct child of the parent. If it is not a direct child, the method will throw a NotFoundError.
If you only have a reference to the element to be removed from its parent, use the remove() method on it.
Keep in mind that when removing an element, the element can still exist if you retain a reference to it. It is just removed from its parent.
For the code example, the same HTML will be used, as follows:
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>Document Object Model Example</title>
</head>
<body>
<h1>Fruits List</h1>
<ul>
<li id="li-apple" class="fruit">Apple</li>
<li class="fruit">Banana</li>
<li class="fruit">Orange</li>
</ul>
</body>
</html>
This is a code snippet using all of these functions.
// Select unordered list and list element
const fruitUl = document.querySelector("ul");
const appleLi = document.getElementById("li-apple");
// Remove child with the help of a reference to its parent
fruitUl.removeChild(appleLi);
// Create a new element that would be represented with a <li> tag if it were in HTML
const newLi = document.createElement("li");
// Set the text of the new element and its class
newLi.textContent = "Grape";
newLi.classList.add("fruit");
// Add the new list item to the unordered list
fruitUl.appendChild(newLi);
// Remove the list item without the help of its parent's reference
// This is intentional and just to demonstrate how these methods work
// You won't see it on screen
newLi.remove();
Debugging JavaScript
JavaScript can be very hard to debug! Unlike many other programming languages, JavaScript is very permissive, which means it lets certain mistakes occur without causing an error. Your code can execute perfectly, whilst still producing an incorrect result, or none at all. You can use your browser's developer tools to access important debugging tools, like the JavaScript console. You can also use the console.log(), console.warn(), and console.error() methods to print important debugging information to the console, like variables, state information, and anything else.
Conclusion
You just learned the fundamentals of making interactive webpages using JavaScript and DOM manipulation! Keep in mind, this is not the end! You still have a lot more practice to do to really sharpen your skills! Try to think of a few ideas to practice this with!
If you need help finding some exercises, I made some for you!
-
Fahrenheit to Celsius Converter: You can make a webpage that displays a number input for Fahrenheit, a submit button, and then an element below that will show the Celsius conversion. If you do not feel like using the form tags, you can connect the 'click' event listener on the button to a custom function. This function should reference the Fahrenheit-to-Celsius conversion equation, which is: C = (F - 32) / 1.8. If you don't know how to do arithmetic in JavaScript, it is, in fact, very easy. You can implement the equation as follows:
let celsius = (fahrenheit - 32) / 1.8. Remember, thetextContentproperty can edit the visible text of an element. -
Add Image on Button Click: This one should be simple! In this example, you will create an image element and append it to the document when a specific button is clicked. The
srcproperty allows you to change the source of an image. -
To-do List: You will have a text input, an add button, and an ordered or unordered list of items. When the user clicks the add button, your custom function to make a new list element, change its
textContentto the text in the input (you can use the.valueproperty to find it), and add it to the list. If you want to make it a bit more advanced, you can make each list element have a delete button that is automatically added, which deletes the list item when pressed.
Once you are able to do all of these well, you should progress to making webpages that actually mean something. If you want any more ideas, check out 100 JavaScript Projects for Beginners and 40 JavaScript Projects for Beginners. You absolutely do not need to do all of them! They are just extra help and ideas, in case you need them.
If you have any questions about anything you see in the article, or anything else even remotely related to it, feel free to ask it in the comments below. If you think there's anything else people should know about this topic, you should also leave a comment below so other people can see it. I will respond to each and every comment, unless this gets to like 1,000 comments or something like that.
Top comments (1)
If anyone has any questions or anything they'd like to share, feel free to drop it here in the comments!