JavaScript code not working!

Hi all,
This is my index.html page code -

<!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>
<script src="index.js"></script>
</body>
</html>

And below is my index.js code -

var liWord = document.firstElementChild.lastElementChild.lastElementChild.lastElementChild;
liWord.innerHTML="Priyanka";

But when I run index.html in browser, nothing happens i.e. here I wanted to replace the last list item name from “Third” to something else for example my name “Priyanka” but even after refreshing the browser nothing changes!!
Plz help… is there anything wrong in the code?

Welcome to the forum!

Whenever your code is not working, you can start logging results to the console to see what your code is actually doing.

I would suggest adding this console.log so you can better understand why the text is not showing up

console.log(document.firstElementChild.lastElementChild.lastElementChild.lastElementChild);

I would suggest removing the firstElementChild.lastElementChild stuff and using queryselector instead.

Since you want to use the last element of the unordered list you can use the last child selector

const lastListItem = document.querySelector("ul li:last-child");

Then you can use the textContent property to change the text to something else

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.