// Select the first element in the document with the class name ".item"
const firstItem = document.querySelector(".item");

// Select within a specific element
const container = document.getElementById("container");
const nestedButton = container.querySelector("button.primary");

// When no matching element exists
const notExist = document.querySelector(".no-such-class"); // Returns null
// Called on the Document object (entire document)
document.querySelector(selectors)

// Called on an Element object (specific element)
element.querySelector(selectors)
<div class="container">
    <p>This is a descendant element.</p>
</div>
const container = document.querySelector(".container"); // Select the container element

const matched = container.querySelector("p"); // Find the first <p> within the container
/* This returns the same element as document.querySelector(".container p") */
<div id="my-element">This element's style will be changed.</div>
const element = document.querySelector("#my-element");

element.style.backgroundColor = "lightblue";
element.style.color = "darkblue";
<button id="my-button">Click Me</button>
const button = document.querySelector("#my-button");

button.addEventListener("click", () => {
    alert("Button clicked!");
});
<ul id="my-list"></ul>
const myList = document.querySelector("#my-list");
const items = ["Item 1", "Item 2", "Item 3"];

for (let i = 0; i < items.length; i++) {
    let listItem = document.createElement("li");
    listItem.textContent = items[i];
    myList.appendChild(listItem);
}
<!DOCTYPE html>
<html lang="en">
<head>
    <title>querySelector() Example</title>
</head>
<body>
    <div id="my-element">This element can be selected.</div>
    <script>
        const nonExistentElement = document.querySelector("#non-existent-element");

        if (nonExistentElement === null) {
            console.log("No matching element found.");
        } else {
            console.log("Matching element found.");
        }
    </script>
</body>
</html>