2
I’m practicing Javascript and decided to make a simple To Do List.
I realized that my program identifies the variable tableTask
memso without me declaring it. I delete the line let tableTask = document.querySelector("#tableTask")
and it will continue to function.
I haven’t declared anywhere else. How this is working?
var quantTasks = 1
const buttonForm = document.querySelector("#buttonForm")
buttonForm.addEventListener("click", function() {
event.preventDefault()
tempTr = createTr()
createTd(tempTr)
let tableTask = document.querySelector("#tableTask")
tableTask.appendChild(tempTr)
quantTasks++
document.querySelector("#formTask").reset()
})
function createTr() {
let tempTr = document.createElement("tr")
tempTr.classList.add("task"+quantTasks)
return tempTr
}
function createTd() {
let tempIndice = document.createElement("td")
tempIndice.classList.add("infoIndice")
tempIndice.textContent = quantTasks
let tempTask = document.createElement("td")
tempTask.classList.add("infoTask")
let textTask = document.querySelector("#formTask").inputTask.value
tempTask.textContent = textTask
tempTr.appendChild(tempIndice)
tempTr.appendChild(tempTask)
}
function addToTable(tempRow) {
}
#infoTask {
width: 500px;
background-color: #c7d5e6;
border-radius: 20px;
padding: 5px 10px;
font-family: 'Roboto', sans-serif;
}
#infoIndice {
background-color: #c7d5e6;
border-radius: 20px;
padding: 5px 10px;
font-family: 'Roboto', sans-serif;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
<title>Easy Task</title>
</head>
<body>
<table>
<tbody id="tableTask">
<tr id="infoBar">
<td id="infoIndice">Nº</td>
<td id="infoTask">Task</td>
</tr>
</tbody>
</table>
<form action="" id="formTask">
<input id="inputTask" type="text" name="inputTask">
<button id="buttonForm">Task</button>
</form>
<script src="task.js"></script>
</body>
</html>
That’s because you declared a
id
with the nametableTask
in your HTML. Your browser indexes the ids it finds in HTML, and adds them to yourwindow
, so you can access them as global variables. But this behavior only exists because of compatibility with old websites, it is not a standard, and so should be discouraged, because different browsers may not have the same behavior. Try to initialize your variables manually.– Andre
I realized that the variable had the same name of Id most wanted someone with more experience talking about because I thought it would be too "ganbiarra" to leave like this. Thank you for the information.
– Daniel Carvalho de Oliveira