I'm learning about using keyword "this" with DOM manipulation in JavaScript and I have a missunderstand. Maybe someone can help me to understand it.
For example I have this simple 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("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("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("This 3 = " + this);
}
for (var i = 0; i < li.length; i++) {
li[i].addEventListener("click", changeClass)
}
button.addEventListener("click", addListAfterClick)
input.addEventListener("keypress", addListAfterKeypress)
It is a simple list, and you can add new elements in the list, also you can change the class of an element when you click on an element of the list.
When I refresh the browser I get in the console: This 1 = [object Window]
After that I type a letter in the box and click the "Enter" button and I get in the console: This 2 = [object Window]. So, the object is still "Window".
After that I click on an element from the list and I get in the console: This 3 = [object HTMLLIElement]. I see that the object is changed from Window to HTMLLIElement.
I don't understand when the object is changed from Window to HTMLLIElement. Why the object for This 2 is Window and the object for This 3 is HTMLLIElement. Thank you!