Using the keyword "this" in JavaScript for manipulating the DOM

Struggling to grasp the concept of using the keyword "this" for DOM manipulation in JavaScript? I could really use some help understanding it better.

Consider this basic program:

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript + DOM</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <h1>Shopping List</h1>
    <p id="first">Get it done today</p>
    <p class="second">No excuses</p>
    <input id="userinput" type="text" placeholder="enter items">
    <button id="enter">Enter</button>
    <ul>
        <li class="three">Notebook</li>
        <li>Jello</li>
        <li>Spinach</li>
        <li>Rice</li>
        <li>Birthday</li>
        <li>Candles</li>
    </ul>
    <script type="text/javascript" src="script.js"></script>
</body>
</html>

style.css:

.done {
    text-decoration: line-through;
}

script.js:

var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");
var li = document.getElementsByTagName("li"); 

console.log("Understand This 1 = " + this);

function inputLength() {
    return input.value.length;
}

function createListElement() {
        var li = document.createElement("li");
        li.appendChild(document.createTextNode(input.value));
        ul.appendChild(li);
        console.log("Understand This 2 = " + this);
        input.value = "";
}

function addListAfterClick() {
    if (inputLength() > 0) {
        createListElement();
    } 
}

function addListAfterKeypress(event) {
    if (inputLength() > 0 && event.keyCode === 13) {
        createListElement();
    }
}

function changeClass() {
        this.classList.toggle("done");
        console.log("Understand This 3 = " + this);
}

for (var i = 0; i < li.length; i++) {
    li[i].addEventListener("click", changeClass)
}

button.addEventListener("click", addListAfterClick)

input.addEventListener("keypress", addListAfterKeypress)

This program allows you to add new elements to a list and change the class of an element when clicking on it.

Upon refreshing the browser, the console displays: Understand This 1 = [object Window]

After entering a letter in the textbox and clicking "Enter", the console shows: Understand This 2 = [object Window]. The object remains as "Window".

However, upon clicking an element in the list, the console outputs: Understand This 3 = [object HTMLLIElement]. It's interesting to note the shift from Window to HTMLLIElement.

I am confused about the transition from Window to HTMLLIElement. Why does This 2 show Window while This 3 changes to HTMLLIElement? Thank you in advance!

Answer №1

Upon refreshing the browser, I am greeted with a message in the console: This 1 = [object Window]

When in global code, this refers to the global (window in a browser) object.

Subsequently, upon typing a letter in a box and clicking the "Enter" button, the console displays: This 2 = [object Window]. It appears that the object remains as "Window".

During a function call, if this is not explicitly defined, it defaults to the global/window object. In strict mode code, it would be undefined.

After clicking on an element from a list, the console logs: This 3 = [object HTMLLIElement]. The object has now changed from Window to HTMLLIElement.

When a function added as a listener using addEventListener is triggered, its this will be set to the element the listener is attached to, similar to:

changeClass.call(element, event)

The event associated with the action is passed as the first argument.

I am puzzled by the transition of the object from Window to HTMLLIElement. Why does This 2 refer to Window while This 3 points to HTMLLIElement?

this acts as a parameter within an execution context, which is established when the context is generated. It can be determined during the call or through bind, or inherited in arrow functions lexically (derived from the outer execution context). Refer to How does the “this” keyword work?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When the canvasJS range column chart is below the horizontal axis, modify the color and width of the bars

For each day of the week, there are records of fuel consumed and refilled. I envisioned representing this data in a range column chart using CanvasJS library. The unique aspect is that the color and width of the bars should change dynamically based on thei ...

Instructions for securing a React Front End with Node.js Express-Sessions authentication:

I have decided to move away from using Firestore auth in order to develop my own authentication system. Here is my goal: To create a React web app that allows users to sign up and sign in. Authenticated users should be able to interact with a REST API, w ...

Executing a pair of queries within the same table and integrating them within a unified route

How can I efficiently execute two queries on the same table in my project? I have been considering using promises, but my knowledge on them is limited. Even though I've researched about it, I am struggling to implement the correct structure. My main ...

Refining search outcomes using multiple Multiselect boxes in VueJS

In my Vue component, I have successfully displayed results from a data object and created multiple multiselect boxes. However, I am facing challenges with filtering. I understand how to set and compare a single value from the multiselect for displaying sp ...

obtain hyperlinks on a website

Is it possible to retrieve links from a web page without actually loading it? Essentially, I would like to allow a user to input a URL and then extract all the available links within that webpage. Do you know of any method for accomplishing this task? ...

Verify if the JSON attribute is empty

My input contains the following: { "headers": { ... }, "body": { "RequestInfo": { ... , "Identificator": null } } <filter regex="false" source="boolean($ctx:Identificator)"> - check if it exists (even when it's ...

Troubleshooting issue with jQuery/Javascript custom email validation not functioning as expected

I attempted to create my own email validation without using a plugin, but it's not functioning correctly. The code I wrote always returns false. Here is the snippet: var regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i; ...

Automatically setting the checkbox for each unique ID based on database values for the specified hobby

Query: The issue I am facing is that when I click the edit button for the first time, the checkboxes get checked based on the values in the database table. However, when I click another edit button for the second time, the checkboxes do not get unchecked f ...

JavaScript Processing Multiple Input Values to Produce an Output

Hello, I am working on creating a stamp script that will allow users to enter their name and address into three fields. Later, these fields will be displayed in the stamp edition. Currently, I have set up 3 input fields where users can input their data. He ...

How to iterate through a Vue data object using forEach loop

I am currently working with a variable in my data: data: function () { return { myVariable: false, } } I'm trying to figure out how to access this variable within a looping function, like the example below: anArray.forEach(functi ...

Bring in an HTML page into a DIV element by utilizing .load with jQuery

I have a PHP function that generates and returns HTML content, and I want to display that content in a DIV when the page loads. Currently, I am attempting to do this by: <div id="myModal" class="reveal-modal" title="El Farol" data-animation="fade"> ...

Tips on bringing data from a php file into a javascript variable

I'm faced with a challenge where I need to extract data from a MySQL database using a PHP file and then store that data in a JavaScript array for plotting purposes with jQuery's flot library. Has anyone encountered a similar situation and found a ...

JavaScript code does not seem to be functioning properly on my computer, but it works perfectly fine on

While the code functions perfectly in JSFiddle, it seems to fail when I try to implement it in an HTML file. Despite my efforts, I am unable to pinpoint the source of the issue. If you'd like to view the working version, here is the Fiddle demo. Bel ...

Seeking to develop a pair of functions for submitting data via my website's form

I need to pass form data to both Docusign and Zapier with just one button click using JavaScript. When the Submit button is pressed, I want the data to be sent to Zapier without opening a success page and then redirect to the Docusign page with all the in ...

Guide on utilizing Chrome Push Notifications on an HTTP website

I'm looking to incorporate Chrome push notifications (GCM) on my HTTP site. I've read that it's typically only for HTTPS sites, but is there a workaround or sample code available for integrating push notifications on an HTTP site? I'm ...

After making a request with HttpClient, the response can either be an empty body or a body

Encountering issues with HttpClient while trying to post data, I am faced with two distinct errors: When booking is treated as an object, the error message reads: Backend returned code 400, body was: [object Object]. Converting booking to JSON format by ...

Addressing memory leaks in React server-side rendering and Node.js with setInterval

Currently in my all-encompassing react application, there's a react element that has setInterval within componentWillMount and clearInterval inside componentWillUnmount. Luckily, componentWillUnmount is not invoked on the server. componentWillMount( ...

Is it feasible to retrieve an object from AWS S3 in Blob format using AWS SDK for JavaScript V3?

Currently, I am working on a project utilizing Next.js and I am facing the task of uploading photos to a Bucket S3. In order to stay up-to-date with the latest technology, I have chosen to utilize the latest version (3) of AWS SDK for JavaScript. After se ...

There seems to be an issue with the React 15 setState function not working on

My react setState after action isn't functioning properly. handleChange = () => { this.setState({foo: 'bar'}); < - it's working console.log('hellow') < - not working, console is clean } I have double-check ...

Having trouble with the import of the directory's index file?

The code snippet in application.js indicates that the "home" imported from "./routes/index" is undefined. import {home} from "./routes/index" console.log(JSON.stringify(home, null, 4)) This is what index.js contains: export * from "./home.js" And here ...