Targeting the DOM

Targeting Parts of the Window

A major part of JavaScript is the ability to target specific parts of the DOM such as an element, class, ID, or integral browser component.

The term Global Window Object represents the browser window. You can access things inside it or its own built-in methods. Common ones are listed below but a full list is available in the MDN developer documentation.

Pop-ups

window.alert('message')

This window method causes a pop up to appear in the browser containing 'message'. A good use case of this for when you need to display information to the user such as an error occurring or perhaps a confirmation message when a form has been submitted or similar action completed.

HTML

<button id="window-alert-example-button-id">
    Press here to show an example window alert.
</button>

JavaScript

// Check that the document has loaded first
document.addEventListener('DOMContentLoaded', function () {
    // Get the button as a variable by targeting the ID
    const exampleButton = document.getElementById('window-alert-example-button-id')
    // Add an event listener to the button to check for a click
    exampleButton.addEventListener('click', function() {
        // Add a function that shows the alert
        window.alert('Button Clicked!');
    })
});

Result

window.prompt('Prompt text')

This window method opens up a dialogue box for the user to enter some information. It will return the string of whatever the user enters or null if it is cancelled.

HTML

<button id="window-prompt-example-button-id">
    Press here to show an example window prompt.
</button>

JavaScript

// Check that the document has loaded first
document.addEventListener('DOMContentLoaded', function () {
    // Get the button as a variable by targeting the ID
    const exampleButton = document.getElementById('window-prompt-example-button-id')
    // Add an event listener to the button to check for a click
    exampleButton.addEventListener('click', function() {
        // Add a function that shows the prompt
        // Save the user response to a variable
        let userResponse = window.prompt('Enter a prompt!');
        // Do something with the response
        earlierDefinedFunction(userResponse);
    })
});

Result

window.confirm('Confirmation Message')

This window method opens a pop up for the user to confirm or cancel something. It returns true if confirmed or false if cancelled.

HTML

<button id="window-confirm-example-button-id">
    Press here to show an example window confirmation.
</button>

JavaScript

// Check that the document has loaded first
document.addEventListener('DOMContentLoaded', function () {
    // Get the button as a variable by targeting the ID
    const exampleButton = document.getElementById('window-confirm-example-button-id')
    // Add an event listener to the button to check for a click
    exampleButton.addEventListener('click', function() {
        // Add a function that shows the prompt
        // Save the user response to a variable
        let userResponse = window.confirm('Confirm?')
        // Do something with the response
        earlierDefinedFunction(userResponse);
    })
});

Result

Window Dimensions

In some cases you may want to us the window dimensions, this is the syntax for accessing it. The examples follow syntax for sections not yet covered but they follow the process of assign the value to a variable, get the element that will show the result, and set that element's content to the variable.

window.innerWidth and window.innerHeight

These return the viewport size including scroll bars but not toolbars or menus.

HTML

<button id="window-inner-example-button-id" class="site-button">
    Press here to show the window inner heights and width.
</button>
<div>
    <p>The window inner width is:<span id="window-inner-width-result-id"></span>.</p><br>
    <p>The window inner height is:<span id="window-inner-height-result-id"></span>.</p>
</div>

JavaScript

// Check that the document has loaded first
document.addEventListener('DOMContentLoaded', function () {
    // Get the button as a variable by targeting the ID
    const exampleButton = document.getElementById('window-inner-example-button-id');
    // Add an event listener to the button to check for a click
    exampleButton.addEventListener('click', function() {
        // Add a function
        // Get the result spans
        let innerWidthResultSpan = document.getElementById('window-inner-width-result-id');
        let innerHeightResultSpan = document.getElementById('window-inner-height-result-id');
        // Get the height and width
        const innerWindowWidth = window.innerWidth;
        const innerWindowHeight = window.innerHeight;
        // Set the contents of the result spans to the height and width results
        innerWidthResultSpan.innerHTML = innerWindowWidth;
        innerHeightResultSpan.innerHTML = innerWindowHeight;
    })
});

Result

The window inner width is: ? pixels.


The window inner height is: ? pixels.

window.outerWidth and window.outerHeight

These return the total window size including browser interfaces such as menus

HTML

<button id="window-outer-example-button-id" class="site-button">
    Press here to show the window outer heights and width.
</button>
<div>
    <p>The window outer width is:<span id="window-outer-width-result-id"></span>.</p><br>
    <p>The window outer height is:<span id="window-outer-height-result-id"></span>.</p>
</div>

JavaScript

// Check that the document has loaded first
document.addEventListener('DOMContentLoaded', function () {
    // Get the button as a variable by targeting the ID
    const exampleButton = document.getElementById('window-outer-example-button-id');
    // Add an event listener to the button to check for a click
    exampleButton.addEventListener('click', function() {
        // Add a function
        // Get the result spans
        let outerWidthResultSpan = document.getElementById('window-outer-width-result-id');
        let outerHeightResultSpan = document.getElementById('window-outer-height-result-id');
        // Get the height and width
        const outerWindowWidth = window.outerWidth;
        const outerWindowHeight = window.outerHeight;
        // Set the contents of the result spans to the height and width results
        outerWidthResultSpan.innerHTML = outerWindowWidth;
        outerHeightResultSpan.innerHTML = outerWindowHeight;
    })
});

Result

The window outer width is: ? pixels.


The window outer height is: ? pixels.

URL and Navigation

It's handy on occasion to be able to get the data from the URL for confirmation or browser manipulation.

window.location

This gives full access to the URL info as a location object. You can use window.location.href to get the full URL from the current page along with hostname, pathname, protocol, search etc. to get different specific information.

HTML

<button id="window-location-example-button-id" class="site-button">
    Press here to show the URL information.
</button>
<div>
    <p>The full URL information is: <span id="window-location-full-result-id">?</span>.</p><br>
    <p>The current page is: <span id="window-location-current-result-id">?</span>.</p>
</div>

JavaScript

// Check that the document has loaded first
document.addEventListener('DOMContentLoaded', function () {
    // Get the button as a variable by targeting the ID
    const exampleButton = document.getElementById('window-location-example-button-id');
    // Add an event listener to the button to check for a click
    exampleButton.addEventListener('click', function() {
        // Add a function
        // Get the result spans
        let fullInformationResultSpan = document.getElementById('window-location-full-result-id');
        let currentPageResultSpan = document.getElementById('window-location-current-result-id');
        // Get the URL information
        const fullInformation = window.location;
        const currentPage = window.location.href;
        // Set the contents of the result spans to the height and width results
        fullInformationResultSpan.innerHTML = fullInformation;
        currentPageResultSpan.innerHTML = currentPage;
    })
});

Result

The full URL information is: ?.


The current page is: ?.

window.history

This represents the session history of the browser tab. You can use window.history.back or window.history.forward to move the page back or forward one just like the back and forward buttons in your browser. Due to security concerns, you cannot get a list of your URL history through JavaScript.

HTML

<button id="window-history-example-button-id" class="site-button">
    Press here to show your window history information.
</button>
<div>
    <p>Your window history information is:</p>
    <ul id="window-history-result-id"></ul>
</div>

JavaScript

// Check that the document has loaded first
document.addEventListener('DOMContentLoaded', function () {
    // Get the button as a variable by targeting the ID
    const exampleButton = document.getElementById('window-history-example-button-id')
    // Add an event listener to the button to check for a click
    exampleButton.addEventListener('click', function() {
        console.log("Button pressed")
        // Add a function
        // Get the result unordered list
        let historyInformationList = document.getElementById('window-history-result-id');
        // Get the history information
        const historyInformation = window.history;
        // Clear previous content
        historyInformationList.innerHTML = '';
        // Loop through the properties of the history object
        for (let key in historyInformation) {
            // Create a list element
            const li = document.createElement('li');
            // Add the information to the list element
            li.textContent = `${key}: ${historyInformation[key]}`;
            console.log('Pressed')
            // Add the list element to the unordered list
            historyInformationList.appendChild(li);
        }
    })
});

Result

Your window history information is:

    Data Storage

    window.localStorage

    This stores key, value pairs in the browser that stay there after the page is closed. These are used mainly for user preferences. In fact, I use them on this website for the light/dark mode toggle. Otherwise going to a new page would reset it to light mode. My code for this functionality is:

    // Make sure that the document has loaded
    document.addEventListener("DOMContentLoaded", function () {
        // Get the day/night select buttons from the dropdown
        const dayButton = document.getElementById("day-mode");
        const nightButton = document.getElementById("night-mode");
        // Get the dropdown itself
        const modeToggleButton = document.getElementById(
            "day-mode-toggle-dropdown"
        );
    
        // Highlight JS CDN links (this changes the day/night mode of the code examples)
        const hightlightJsCDN = document.getElementById('highlightjscdn');
    
        // Create a function to set the initial mode
        function setSelectedMode(mode) {
            // If the mode has the value of the fontawesome sun icon passed into it
            if (mode === "<i class='fa-solid fa-sun'></i>") {
                // Add the active class to the day button
                dayButton.classList.add("active");
                // Remove the active class from the night button
                nightButton.classList.remove("active");
                // Set the toggle button to show the day mode
                modeToggleButton.html = "<i class='fa-solid fa-sun'></i>";
                // Update the day/night mode of the code examples
                hightlightJsCDN.setAttribute('href', 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css');
            // Otherwise if function is run without the fontawesome sun icon
            } else {
                // Add active class to the night button
                nightButton.classList.add("active");
                // Remove active class from the day button
                dayButton.classList.remove("active");
                // Change the drop down button to show a mood
                modeToggleButton.html = "<i class='fa-solid fa-moon'></i>";
                // Update the day/night mode of the code examples
                hightlightJsCDN.setAttribute('href', 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/atom-one-dark.min.css');
            }
        }
    
        // Event listeners for changing modes
        // If the day mode button is clicked
        dayButton.addEventListener("click", function () {
            // Remove night-mode class from the body element
            document.body.classList.remove("night-mode");
            // Add day-mode class to the body element
            document.body.classList.add("day-mode");
            // Save the preference as the key:value of theme: day
            localStorage.setItem("theme", "day");
            // Run the setSelectedMode function with the fontawesome sun icon
            setSelectedMode("<i class='fa-solid fa-sun'></i>");
            // Update the day/night mode of the code examples
            hightlightJsCDN.setAttribute('href', 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css');
        });
    
        // If the night mode button is clicked
        nightButton.addEventListener("click", function () {
            // Remove day-mode class from the body element
            document.body.classList.remove("day-mode");
            // Add night-mode class to the body element
            document.body.classList.add("night-mode");
            // Save the preference as the key:value of theme: night
            localStorage.setItem("theme", "night");
            // Run the setSelectedMode function with the fontawesome oon icon
            setSelectedMode("<i class='fa-solid fa-moon'></i>");
            // Update the day/night mode of the code examples
            hightlightJsCDN.setAttribute('href', 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/atom-one-dark.min.css');
        });
    
        // Initialize each page with the chosen mode
        // Use localstorage to get the value from the key "theme"
        const storedTheme = localStorage.getItem("theme");
    
        // If the value is night
        if (storedTheme === "night") {
            // Add night-mode class to the body
            document.body.classList.add("night-mode");
            // Remove day-mode class from the body
            document.body.classList.remove("day-mode");
            // Run setSelectedMode with the fontawesome moon icon
            setSelectedMode("<i class='fa-solid fa-moon'></i>");
            // Update the day/night mode of the code examples
            hightlightJsCDN.setAttribute('href', 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/atom-one-dark.min.css');
        } else {
            // If the value is not night
            // Add day-mode class to the body
            document.body.classList.add("day-mode");
            // Remove night-mode class from the body
            document.body.classList.remove("night-mode");
            // Run setSelectedMode with the fontawesome sun icon
            setSelectedMode("<i class='fa-solid fa-sun'></i>");
            // Update the day/night mode of the code examples
            hightlightJsCDN.setAttribute('href', 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css');
        }
    });
    

    Targeting Parts of the Document

    Getting Elements of the Document

    Similarly, the document is also an object and can has methods associated with them. A full list can be found in the MDN developer documentation.

    For major elements such as the <head> and <body> elements, you can target them directly, along with some others.

    // Get the head element
    document.head
    // Get the body element
    document.body
    // Get the HTML element (root of the document)
    document.documentElement
    // Get the title element inside the head element
    document.title
    // Get a HTMLCollection of all form elements
    document.forms
    // Get a HTMLCollection of all img elements
    document.images
    // Get a HTMLCollection of all anchor elements
    document.links
    // Get a HTMLCollection of all script elements
    document.scripts
    // Get a StyleSheetList of all linked CSS stylesheets 
    document.styleSheets
    

    For other element tags you need the following syntax for, in this example, paragraphs. To target other elements, replace p with their tag. This returns all of the elements with that tag name as a HTMLCollection.

    document.getElementsByTagName('p');
    

    To target elements by their class names and return them as a HTML collection, use the following syntax. This is one of the most used methods along with targeting the ID of an element, as it gives you precise control over what is affected on your page.

    document.getElementsByClassName('class-name');
    

    To target an element based on its ID, use the following syntax. If the ID cannot be found, it will return null.

    document.getElementById('id-name');
    

    Troubleshooting

    • If you are failing to target the class or ID, double check the 's' in getElementsByClassName() or the lack of 's' in getElementById().

    You can also select elements based on CSS selectors. This returns the first element of whatever is in the brackets. This uses CSS selectors using CSS syntax for selecting elements inside quotation marks, so valid values are:

    • '#id-name'
    • '.class-name'
    • 'tag-name' (e.g. 'h1' or 'p')
    • Any other valid CSS selector such as 'div > p'
    document.querySelector();
    

    To return all elements that match the given criteria as a NodeList use the following. This is useful for when you want to loop through it or affect all of one type (class, tag, etc.).

    document.querySelectorAll();
    

    Aspects of the Elements

    Now we know how to target specific elements, we can target their contents and information about them using dot notation.

    .innerText
    

    Returns the text value. Remember, JavaScript uses dot notation to link methods together, so to return the text of the first h1 element, you could use document.querySelector('h1').innerText.

    .value
    

    Returns the value of, for instance, form elements. It reflects what the user has entered rather than the text of the HTML element (like .innerText does).

    .innerHTML
    

    Returns the HTML content of the element including any nested HTML tags.

    .item()
    

    If you targeted a collection, such as by using .getElementsByClassName(), you can use this to target a specific item in that list, which will returns the item at the specified index (starting at 0).

    .length()
    

    Returns the amount of items in the list.

    .namedItem()
    

    Returns the element with the specific ID or name if it exists in the collection.

    Parents and Children

    Once you have an element set to a variable you can access others via their relative position in the DOM family tree.

    • variable.parentNode; Get the elements parent. document.parentNode returns null because it is the root node
    • variable.children; Get the elements children. If there are no children; it returns null
    • variable.children[0]; Get the first child
    • variable.firstElementChild; Same as above
    • variable.lastElementChild; Returns the last child
    • variable.nextElementSibling; Get the next element of the same nest level
    • variable.previousElementSibling; Get the previous element of the same nest level
    • variable.parentElement; Get the parent element