Welcome back. In our previous lesson, we built a static HTML page with a login form. That page has structure, but it's passive; it can't react to the user on its own. Today, we'll introduce JavaScript, the programming language of the web, which allows us to bring our pages to life.
This lesson focuses on a core JavaScript skill: manipulating the Document Object Model (DOM). The DOM is the browser's internal representation of your HTML, and by using JavaScript, you can change it dynamically. Our goal is for you to be able to write simple scripts that select HTML elements, change their content or attributes, and respond to user actions like clicks. For your goal of bug bounty hunting, this is not just a foundational skill—it's the key to understanding, finding, and exploiting most client-side vulnerabilities like Cross-Site Scripting (XSS).
What is the DOM?
When a browser loads an HTML document, it creates a model of that page in memory. This model, the Document Object Model, represents the document as a tree of objects. Each HTML tag, like <body>, <h1>, or <p>, becomes a "node" in this tree. JavaScript can access and manipulate this tree, allowing you to add, remove, or change any part of the HTML after the page has loaded.
Learn JavaScript DOM Manipulation – Tutorial for Beginners
The video "Learn JavaScript DOM Manipulation" provides a great visual and conceptual introduction to the DOM.
Watch the very beginning of the video to understand how the DOM is structured like a tree and how each HTML element becomes an object that JavaScript can control.
Selecting and Modifying Elements
To manipulate an element, you first need to select it. JavaScript provides several methods to grab a reference to a specific node in the DOM tree. Once you have that reference, you can change its properties.
Let's set up your environment. Open the index.html file containing the login form from our last lesson in VS Code. Create a new file in the same folder called script.js. To connect your JavaScript to your HTML, add the following line just before the closing </body> tag in your index.html file:
<script src="script.js"></script>
Now, any code you write in script.js will run on your HTML page.
The most common ways to select elements are:
document.getElementById('some-id'): Selects the single element that has the matchingidattribute. This is very fast and precise.document.querySelector('some-css-selector'): A more versatile method that selects the first element matching a CSS selector. You can use it to find an element by ID (#username), by class (.btn), or by tag name (button).document.querySelectorAll('some-css-selector'): Similar toquerySelector, but it returns a list of all elements that match the selector.
Once an element is selected, you can create new content and add it to the page.
Learn JavaScript DOM Manipulation – Tutorial for Beginners
The same video will now demonstrate how to select elements and add new content.
Watch the segment from this section to see how getElementById and querySelector are used. Pay close attention to the distinction between append() (which can add text or elements) and appendChild() (an older method). The video also introduces document.createElement(), which is how you create new HTML elements from scratch in JavaScript.
Changing Element Content: innerText, textContent, and innerHTML
There are a few ways to change the content inside an element you've selected.
element.innerTextandelement.textContent: Both are used to set or get the text content of an element. They have a subtle difference:innerTextis aware of the page's styling and will only show "human-readable" text, whiletextContentwill return all text content, including that of hidden elements.element.innerHTML: This property is much more powerful and, from a security perspective, much more dangerous. It gets or sets the entire HTML content—tags and all—inside an element.
Why is innerHTML dangerous? If you take input from a user (for example, their name or a comment) and place it directly into innerHTML, an attacker could provide a string containing malicious HTML and JavaScript. When the browser renders this string, it will execute the attacker's script. This is the essence of a Cross-Site Scripting (XSS) attack.
Learn JavaScript DOM Manipulation – Tutorial for Beginners
Let's continue with the video to understand these properties, especially the security risk of innerHTML.
First, watch the explanation of the difference between innerText and textContent. Next, and most importantly for your goal, watch the section on innerHTML. The video clearly explains its function and then demonstrates a live XSS attack using it. Pay close attention to this part. This is a classic vulnerability you will be looking for.
As a rule of thumb: Never use innerHTML to insert content that comes from a user or any untrusted source. Always prefer textContent or innerText to safely insert text.
Responding to User Events
Static content modification is useful, but the real power of JavaScript comes from its ability to respond to user actions. You can "listen" for events like clicks, mouse movements, or key presses and execute a function when that event occurs.
The addEventListener() method is the modern, standard way to do this. You call it on an element you've selected, specify the event you want to listen for (e.g., 'click'), and provide a "callback function" to run when the event happens.
Learn JavaScript DOM Manipulation – Tutorial for Beginners
The video provides a clear walkthrough of how to handle events.
Watch the segment on event handling from this clip. It shows you how to add a listener for a click event and introduces the event object, which contains useful information about the event that occurred, such as event.target (the element that was clicked).
Practice: Making Your Login Form Interactive
Let's apply these concepts to the login form you created in the last lesson. We'll add two simple features:
- When the "Log In" button is clicked, we'll log the entered username and password to the browser's developer console instead of trying to submit the form.
- We'll add a "Show Password" checkbox that toggles the password field's visibility.
First, add a checkbox to your index.html file, right after the password paragraph:
<p>
<input type="checkbox" id="show-password">
<label for="show-password">Show Password</label>
</p>
Now, open your script.js file and add the following code:
// 1. Select the elements we need from the DOM
const loginForm = document.querySelector('form');
const usernameInput = document.querySelector('#username');
const passwordInput = document.querySelector('#password');
const showPasswordCheckbox = document.querySelector('#show-password');
// 2. Add an event listener to the form for the 'submit' event
loginForm.addEventListener('submit', (event) => {
// Prevent the form from actually submitting and reloading the page
event.preventDefault();
// Log the values from the input fields to the console
console.log('Username:', usernameInput.value);
console.log('Password:', passwordInput.value);
alert('Check the console for the captured credentials!');
});
// 3. Add an event listener to the checkbox for the 'change' event
showPasswordCheckbox.addEventListener('change', () => {
// Check if the checkbox is checked
if (showPasswordCheckbox.checked) {
// If checked, change the password input type to 'text'
passwordInput.setAttribute('type', 'text');
} else {
// If not checked, change it back to 'password'
passwordInput.setAttribute('type', 'password');
}
});
Let's break down this script:
- We use
querySelectorto get references to the form and its inputs. - We listen for the
submitevent on the form. Theevent.preventDefault()call is crucial; it stops the browser's default behavior of sending the form data to a server and reloading the page. This is a common technique used in modern web apps and something you'll need to understand as a tester. - We then access the
.valueproperty of the input elements to get the text the user typed and log it. - We listen for the
changeevent on the checkbox. Inside the callback, we usesetAttribute()to dynamically change thetypeattribute of the password field, toggling its visibility. This is a practical example of both event handling and attribute manipulation.
Save both files and open index.html in your browser. Open the developer tools (usually F12 or Ctrl+Shift+I) and go to the "Console" tab. Try typing in the form and clicking the button, and toggle the checkbox to see your script in action.
Conclusion
In this lesson, you took a major step from understanding static web structure to manipulating it dynamically. You've learned how to use JavaScript to interact with the DOM, the very foundation of client-side interactivity and, by extension, client-side security testing.
Key Takeaways:
- The Document Object Model (DOM) is a tree-like representation of an HTML page that JavaScript can interact with.
- You can select elements using methods like
querySelectorandgetElementById. - You can change content with
innerTextandtextContent. UsinginnerHTMLwith untrusted data is a major security risk that leads to XSS. addEventListenerallows your code to react to user events likeclick, making pages interactive.- Manipulating element attributes with
setAttributecan change an element's behavior, like toggling a password field's visibility.
We've now covered the three core technologies of the front-end: HTML for structure, and now JavaScript for behavior (CSS, for styling, is less critical for our security focus). In the next lesson, we'll investigate how websites remember who you are across multiple page loads by exploring cookies and session management, a critical area for finding authentication and access control flaws.