var name = document.firstElementChild.lastElementChild.lastElementChild.lastElementChild;
name.innerHTML = "XYZ";
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>My Website</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Hello</h1>
<input type="checkbox">
<button style=":active color:red;">Click Me</button>
<ul>
<li class="list">
<a href="https://www.google.com">Google</a>
</li>
<li class="list">Second</li>
<li class="list">Third</li>
</ul>
</body>
</html>
So, this is the code for a website, and I wanted to change the text of the last element of the document - "Third" changes to "XYZ".
When I use the following code, the text does not change.
var name=document.firstElementChild.lastElementChild.lastElementChild.lastElementChild;
name.innerHTML="XYZ";
However, when I use this:
document.firstElementChild.lastElementChild.lastElementChild.lastElementChild.innerHTML="XYZ";
The text on the website, immediately changes. Why is this happening? All I have done is just split the code in two lines instead of writing it in one.
In the global scope, the name variable is predefined and can only be assigned strings.
You can:
let instead of var to shadow (instead of mapping onto) global variables.