Interactive online courses HTML Academy
2026-03-09 12:23 Diff

Muffin finally dropped by the office and came to see you first. The boss wants to make a few corrections to the page: he wants to let everyone know that screwdriver “Philly” is the product of the day and mark “Mjöllnir” as not being available for order at this time.

It would seem that JavaScript can do nothing here, since it is possible to just change layout or styles. But we do not have access to either of those. Such was the decision of the store owner. We can only change the page using scripts.

JavaScript takes a special approach to layout: elements here are not strings that we write in HTML files, but objects. In this case, each object is associated with other similar objects and knows about its parent, neighboring object elements and nested objects. The result is a tree structure called DOM (Document Object Model).

Each DOM tree has a root object, from which other objects grow. It’s called document. This global object is available in all programs that run in the browser. Simply put, document is a page that contains all the layout elements (objects).

Developers can use document to find any object on the page and then change it. That is why the document object has special search methods.

The most flexible of these is querySelector. This method takes an CSS selector and returns the appropriate element. It understands any CSS selectors and is called like this:

// Searching for an element by tag var list = document.querySelector('ul'); // Searching for the last element from the list var lastProduct = document.querySelector('li:last-child'); // Searching for an element by class name var price = document.querySelector('.price'); // Searching for the third element from the product list var thirdProduct = document.querySelector('.product:nth-child(3)');

Let’s look at the store page. We can see a list where each product is <li> with class product. Screwdriver “Philly” must become the product of the day, the second one in the layout. This means that we need to find the second element in the list. To do this, you can use selector .product:nth-child(2). “Mjöllnir” is out of stock and is the last one position-wise. It can be found with .product:last-child.

Let’s find the second and last DOM element from the list of products, log them in the console and make sure that the search worked correctly.