Revived: Old JavaScript DOM Selector (getElementById/TagName)

By: wesam July 25, 2025 Web Development

Description

This snippet revives an old JavaScript method for selecting DOM elements, commonly used before the widespread adoption of modern selector APIs like `querySelector`. It demonstrates a basic pattern for finding elements by ID or tag name directly, highlighting its historical context in early web development.

Original Code (Outdated)

// Old way to select DOM elements
function oldStyleSelector() {
    // Selecting by ID
    var myDiv = document.getElementById("myOldDiv");
    if (myDiv) {
        myDiv.innerHTML = "Content updated from old JS!";
        myDiv.style.color = "red";
    }

    // Selecting by Tag Name (returns an HTMLCollection)
    var paragraphs = document.getElementsByTagName("p");
    if (paragraphs.length > 0) {
        for (var i = 0; i < paragraphs.length; i++) {
            paragraphs[i].style.fontWeight = "bold";
        }
    }
}

// Dummy HTML elements for testing
document.body.innerHTML += '<div id="myOldDiv">Original Div Content</div><p>First paragraph.</p><p>Second paragraph.</p>';
oldStyleSelector();

Updated Code (Modern)

// Modern way to select DOM elements using querySelector/querySelectorAll
function modernStyleSelector() {
    // Selecting by ID using querySelector (more versatile, returns first match)
    const myDiv = document.querySelector("#myOldDiv");
    if (myDiv) {
        myDiv.textContent = "Content updated from modern JS!"; // Use textContent for security
        myDiv.style.color = "blue";
    }

    // Selecting by Tag Name using querySelectorAll (returns a NodeList, iterable)
    const paragraphs = document.querySelectorAll("p");
    paragraphs.forEach(p => { // Use forEach on NodeList
        p.style.fontWeight = "normal"; // Resetting from old script
        p.style.fontStyle = "italic";
    });
}

// Dummy HTML elements for testing
document.body.innerHTML += '<div id="myOldDiv">Original Div Content</div><p>First paragraph.</p><p>Second paragraph.</p>';
modernStyleSelector();

Discussion (0)