JavaScript JavaScript and the DOM Traversing the DOM Getting the First and Last Child

Viktoria Napolska
Viktoria Napolska
7,237 Points

Changing style of last and first Element after button clicked

Resolve this with code: const listUl = list.querySelector("ul"); const lis = listUl.children; var firstListItem = listUl.firstElementChild; var lastListItem = listUl.lastElementChild;

firstListItem.style.backgroundColor = 'lightskyblue'; lastListItem.style.backgroundColor = 'lightsteelblue'; function clear () { for (var i = 0; i < lis.length; i++) { lis[i].style.backgroundColor = "white"; } } document.addEventListener("click", () => { firstListItem = listUl.firstElementChild; lastListItem = listUl.lastElementChild; clear (); firstListItem.style.backgroundColor = 'lightskyblue'; lastListItem.style.backgroundColor = 'lightsteelblue'; })

Where do you define list? Also please format your code, it makes it easier for us to help.

3 Answers

Steven Parker
Steven Parker
163,772 Points

The HTML part of the code is missing, and there's nothing in the JavaScript that appears to be associated with any button(s).

You may need to explain your issue in more detail, and provide the whole code. The best way to share the entire project is to make a snapshot of your workspace and post the link to it here.

Viktoria Napolska
Viktoria Napolska
7,237 Points

I just try to show my solution of the teacher last task. Everything works. Sorry for bothering you) And thank you for help!)

Steven Parker
Steven Parker
163,772 Points

Sorry for my confusion, I thought you were looking for assistance with a problem.

Say, is that really your pic? I'd swear that was a photo of American actress Laura Harris.

Viktoria Napolska
Viktoria Napolska
7,237 Points

Thank you, but it's really my photo))