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!