JavaScript DOM querySelector and Events: Practical Patterns

Even when a project uses a framework, understanding the browser DOM remains useful. JavaScript's querySelector, querySelectorAll, and event APIs provide a simple foundation for interactive pages.

Selecting an Element

const button = document.querySelector("#saveButton");

CSS selector syntax can be used, so classes, attributes, and nested elements are also supported.

Selecting Multiple Elements

const rows = document.querySelectorAll(".product-row");

rows.forEach(row => {
    console.log(row.textContent);
});

Handling Click Events

const button = document.querySelector("#saveButton");

button.addEventListener("click", () => {
    console.log("Saved");
});

Using addEventListener keeps event behavior separate from markup and allows multiple listeners when needed.

Reading Form Values

const input = document.querySelector("#name");
const value = input.value.trim();

if (!value) {
    alert("Name is required.");
}

Updating the DOM

const message = document.querySelector("#message");
message.textContent = "Saved successfully.";

Prefer textContent for plain text. It avoids interpreting the value as HTML.

Event Delegation

When a list contains many dynamic buttons, attach one listener to the parent rather than creating a separate listener for every item.

document.querySelector("#products").addEventListener("click", event => {
    const button = event.target.closest("button[data-id]");
    if (!button) return;

    console.log(button.dataset.id);
});

DOMContentLoaded

If a script executes before the required markup exists, query selectors can return null. A script loaded in the document head can wait for DOM creation.

document.addEventListener("DOMContentLoaded", () => {
    const button = document.querySelector("#saveButton");
    // safe to use the page elements here
});

Common Mistakes

Conclusion

These DOM patterns cover a large portion of everyday browser scripting. Once selectors, events, forms, and event delegation are understood, it becomes much easier to build small interactive features without unnecessary complexity.

Back to Algolassi Tutorials

🤖 AlgoLassi Assistant Have a question about this tutorial?

Ask AlgoLassi and get an answer plus the tutorials worth studying next.

Ask a question

đŸ’Ŧ Comments

Sign in with Google to publish immediately, or comment anonymously and wait for approval.

Comments will appear here when available.