Menu Home

Getting HTML Elements

Hi everyone, and welcome to another exciting edition of Boring JavaScript! Today, we cover five different ways you can retrieve HTML elements from your webpage.

getElementById()

First, let’s cover one of the simplest ways to get that element – the ‘getElementById’ method. This method will look for an HTMLElement within your webpage that has a certain ‘id’ attribute. If found, it will return that element. Otherwise, it will return null. Let’s take a look:

<body>
    <p>The results of your inquiry is <span id="results">42</span></p>
</body> 

const resultsDom = document.getElementById('results');
console.log(resultsDom);
// prints out the HTMLElement

const notThereDom = document.getElementById('notthere');
console.log(notThereDom);
// prints out null

When you use ‘getElementById’, JavaScript will search your web page for the element that has the attribute ‘id’ that is the value you pass to the method. In the above, there is a ‘<span>’ element that has the ‘id’ of ‘results’, so it will return that element. If the element cannot be found, it will return null.

What if you have more than one ‘id’ with the same value? The results could be unpredictable. Besides, you should never do that, ok?

getElementsByClassName()

You can also return all elements based upon any data defined in the ‘class’ attribute. ‘getElementsByClassName’ will return an HTMLCollection (which acts like an array) of all elements that match the argument. If none do, it will return an empty HTMLCollection. Let’s take a look:

<body>
    <p class="red">You have the following errors in your form:</p>
    <ul class="red">
        <li>Not enough characters</li>
        <li>Didn't answer Question 1</li>
    </ul>
    <div class="green">Please fix the errors above.</div>
</body>
const errorsDom = document.getElementsByClassName('red');
console.log(errorsDom);
// prints an HTMLCollection that contains two HTMLElements (p and ul)

const otherDom = document.getElementsByClassName('orange');
console.log(otherDom);
// prints an empty HTMLCollection

Use ‘getElementsByClassName’ as a way to capture all the elements that have a certain class.

getElementsByTagName()

Simular to ‘getElementsByClassName’, ‘getElementsByTagName’ will return an HTMLCollection of all elements that have a certain tag name. In HTML, a tag name refers to the name of HTML Element, for example ‘P’, ‘DIV’, ‘BODY’, etc. Let’s see how that can be used:

<body>
    <p class="red">You have the following errors in your form:</p>
    <ul class="red">
        <li>Not enough characters</li>
        <li>Didn't answer Question 1</li>
    </ul>
    <div class="green">Please fix the errors above.</div>
</body>
const errorsDom = document.getElementsByTagName('li');
console.log(errorsDom);
// prints an HTMLCollection that contains two HTMLElements (both 'li')

const otherDom = document.getElementsByTagName('select');
console.log(otherDom);
// prints an empty HTMLCollection

What good is this? You can use this method to find custom elements on your page. For example:

<body>
    <vrt-card>This is a Virtuoid Card</vrt-card>
</body>
const virtuoidCards = document.getElementsByTagName('vrt-card');
console.log(virtuoidCards);
// prints an HTMLCollection of one element.

querySelector()

While the above were all well and good, they really limit you in how one could access elements on their web page. You can use CSS to directly point to certain elements – why not here? That is where ‘querySelector’ comes into play. You pass a CSS selector to the ‘querySelector’ method, and it uses that selector to find your element. It will return a single HTMLElement, or null if nothing can be found. Let’s take a look:

<body>
    <section id="group1Errors" class="error">
        <p>You have the following password errors:</p>
        <ul>
            <li>Too few characters</li>
            <li>No numbers</li>
        </ul>
    </section>
    <section id="group2Errors" class="error">
        <p errorlist="true">You have missing fields:</p>
        <ul>
            <li>No entry for field 'name'</li>
        </ul>
    </section>
</body>
const group1Error = document.querySelector('#group1Errors p');
const group2Error = document.querySelector('#group2Errors p[errorlist]');
console.log(group1Error);
console.log(group2Error);
// prints a single HTMLElement for each variable

const otherError = document.querySelector('#nothinghere p');
console.log(otherError);
// prints null

The important thing to remember here is that you pass to ‘querySelector’ a CSS Selector string that JavaScript uses to find your element. It will also return a single element, so if multiple elements match, it will only return the first element.

querySelectorAll()

Exactly like the ‘querySelector’ above, ‘querySelectorAll’ is passed a CSS selector in which it uses to parse your web page. ‘querySelectorAll’, as the name implies, returns all HTML elements that match your selector, returning them in a NodeList. If none are found, it returns an empty NodeList. Let’s take a look:

<body>
    <section id="group1Errors" class="error">
        <p>You have the following password errors:</p>
        <ul>
            <li>Too few characters</li>
            <li>No numbers</li>
        </ul>
    </section>
    <section id="group2Errors" class="error">
        <p errorlist="true">You have missing fields:</p>
        <ul>
            <li>No entry for field 'name'</li>
        </ul>
    </section>
</body>
const group1Errors = document.querySelectorAll('#group1Errors ul li');
const group2Errors = document.querySelectorAll('#group2Errors ul li');
console.log(group1Errors);
// prints a NodeList of the two LI elements inside group1Error;

console.log(group2Errors);
// prints a NodeList of the single LI element inside group2Error

const otherErrors = document.querySelectorAll('#nothinghere ul li');
console.log(otherErrors);
// prints an empty NodeList

One thing to be careful of: ‘Nodelist’, which is the collection returned, looks like an array, but it not an array. You can’t do ‘group1Errors.forEach’, for example. Just a word of warning.

Our Video

As always, we have a video that explains everything – in case you need to fall asleep quickly.

Shameless Plug

Make sure to follow us on the following platforms:

YouTube

Facebook

Categories: Boring JavaScript Javascript

Tagged as:

thevirtuoid

Web Tinkerer. No, not like Tinkerbell.

Creator of the game Virtuoid. Boring JavaScript. Visit us at thevirtuoid.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: