Using JavaScript to Select HTML Elements

One of the most common uses of JavaScript to manipulate elements on a web page. As we learned in the interact with the DOM post, the fist step to manipulating an HTML element is selecting it. The document object that is built into web browser’s JavaScript provides multiple methods that can be used to select an element.

I think it’s important to mention that you will commonly see jQuery mentioned in connection to selecting HTML elements. jQuery is a library (collection of methods and functions) that abstracts many commonly needed actions. I will not cover the use of jQuery in this post as I want to focus mainly on vanilla (plain) JavaScript. Under the hood, jQuery uses the same methods covered here. Old browser versions had inconsistencies in the document object and it’s methods that jQuery helped resolve. Most of these issues have been resolved and the methods covered here are included and standardized across all modern web browsers.

It is assumed that you have a basic understanding of HTML and CSS. If not, then you may find the following difficult to follow. I have placed some excellent HTML and CSS links here that will aid your HTML learning.

getElementById

The method getElementById is the easiest selector method to use. As the name suggests, it finds an element by using its id. Because every ID on valid HTML a page is unique, you know exactly what element it is returning. Of course the element you want to get must have an ID.

The getElementById method takes a string for a parameter and returns the element directly.

Take a look at this interactive code snippet:

See the Pen KbyWYB by Matthew Wilson (@matw) on CodePen.

We have an HTML paragraph with an ID of “foo”. To select this element we use the method getElementById and insert the name of the ID (in our case “foo”) as the first and only parameter. var mySelectedElement = getElementById("foo");.

So now mySelectedElement is set to our HTML element. Our element has many properties, but since in this example we want to change the color we need to update style.color. This can be reassigned to change the elements color and in our example we set it to equal “red”. If you are curious about the other properties on HTML elements see my post here.

getElementsByClassName

Because many elements on a page do not have an id, I find myself using getElementsByClassName a lot more frequently than getElementById. As you might guess from the name, this method returns an array-like-object that contains a collection of elements. This is unlike getElementById which directly returns one element. This means that if you are wanting to select one particular element, you will need to select it from your returned object, however in many cases you may want to perform an action on multiple elements. If this is the case and all your elements have the same class, then the getElementsByClassName works out well.

Let’s look at an example. Say we have a list of names and passwords and we want to hide the passwords on the click of a button. We could do something like this:

See the Pen
Using getElementsByClassName example
by Matthew Wilson (@matw)
on CodePen.

The document.getElementsByClassName('secret') returns an object populated with all the elements that have the class “secret”. We can then use a for..of loop to change the style of each element.

You should also know that getElementsByClassName can be called, not only from the document object, but from any element. It is important to note that it only finds matches that are children of the calling element’s node. This behavior is useful in many situations. Extending the previous example, let’s make our password list have several sections that can be hidden individually. Also let’s reverse the action, instead of hiding our passwords, let’s reveal them on click.

See the Pen
Using getElementsByClassName with children
by Matthew Wilson (@matw)
on CodePen.

There are a few things here that at first may not be clear, so let’s take a closer look. We are using a special keyword “this” as the first parameter in our on-click handler. If you look at the HTML you will see our button section looks like <button onclick="showSecrets(this)">HIDE SECRETS</button>. Here the “this” is actually sending in the button element as a parameter to the showSecrets function. Now we have our calling element inside our function and can use that to our advantage. Since our button and our list items both have a common parent element (the surrounding div) we can use that parent element to call getElementsByClassName and reveal only the passwords in that section.

As you can see from this example, we can use getElementsByClassName’s descendant-only matching behavior to our advantage. If it found every match on the page, we would have to use separate class names or another method to select only one section of passwords to reveal.

Coming soon – Part 2
getElementsByTagNames & querySelector

How to use Javascript to Interact With HTML Webpage

One of the most useful aspects of JavaScript is its ability to manipulate a website. When a pure HTML website loads, that’s it—it’s done and it will not change again until the page is reloaded. Adding JavaScript to a page, however, gives us the ability to update a page even after it has been completely loaded. We’re going to be using the Chrome devTool’s console for this post, so if you don’t know how to open it and use it, please check out the console post for more info.

The HTML Document

The HTML document is composed of elements that are created using tags. HTML tags have the standard format <tagname>Content</tagname>

, and they describe the type of content they contain. For example, to indicate the beginning and end of a paragraph, the content is wrapped using a “p” tag: <p>The paragraph goes here.</p>. W3 School has a great in-depth article here covering HTML tags.

When using JavaScript to manipulate an HTML document, we can use the tags as a road map to navigate and select the document section we want to manipulate.

What is the DOM

When dealing with JavaScript and HTML you will likely hear people refer to the DOM. DOM stands for Document Object Model, and it is essentially an interface that allows JavaScript to access the web page “document.”

To illustrate this point, imagine a string puppet for a minute. If you think of a web page as a puppet, then the DOM could be thought of as the strings and the points at which they attach to the puppet.

Using this same analogy, JavaScript would best be compared to the stick that controls the strings. The DOM allows us to connect JavaScript and HTML together.

Included with a browser’s JavaScript version is an object called the “document.” It is on this object that we can find methods that allow us to interact and manipulate the DOM. Continuing with the analogy, the puppet control sticks have multiple “methods” or actions that can be used to manipulate the puppet.

The DOM is made up of elements that are connected in a tree-like structure. The elements of this tree are objects, and they can be accessed from the root document object mentioned in the previous paragraph.

Navigating the DOM

Before we can manipulate a section of the DOM, we first need to know how to select an element. To help with this, I’ve made a very simple web page that you can experiment with: http://matw.me/example.html. Open this page in a new tab and follow along.

Here is what the HTML code of this example.html page looks like:

<!DOCTYPE html>
<html>

  <head>
  </head>
  <body>
    <div>
      <h1>Div 1 Heading 1</h1>
      <p>Paragraph 1</p>
      <p>Paragraph 2</p>
    </div>
    <div>
      <p>Div 2 Paragraph 3</p>
      <span>
        Text inside span 1.
        <span style="color: blue;">I am a span within a span.</span>
      </span>
    </div>
  </body>
</html>

As you can see, it’s a fairly simple page. There is an inline style to color the nested span blue, but not much else is going on. First off, let’s change the text of the first paragraph.

Before we can manipulate the first paragraph, we have to select it. There are many ways to select an element on a page—you can get elements by class name, id, tag name, or by “walking” up and down the DOM tree. Since the “document” is the DOM root, everything on the web page is a child of the document.

This may be a bit difficult to understand, so let’s take a closer look at it. Go to the example.html page and then open the console. Then type in document.children and press enter. The console should look something like:

Now click the triangle to expand the HTMLCollection object. Can you see how it compares to our HTML code? The first and only child element is the “html” object. This is the root from which everything else on the page stems. Since this is an object, we can save it to a variable. To do that, use var htmlRoot = document.children[0] and press enter. We have to add [0] to the end of our document.children because we want the first child. In JavaScript, the first item is item 0. Now our variable htmlRoot is a reference to the DOM’s html object. Looking back at our page code, you can visualize what this variable references on the page.

Let’s take a look at the HTML’s hierarchical structure:

In the console, we can view the content of our htmlRoot variable. Enter htmlRoot and you should see:

In a tree form, this would look like:

As you can see in the tree above, “html” has two children: “body” and “head.” If we want to navigate to the first paragraph, we have to go through the “body” and then the first “div.” The first paragraph will then be the second child.

Let’s return to navigating to our first paragraph element, and take it one step at a time. Remember the htmlRoot object we created earlier? This is the html element at the top of our tree, so if we enter htmlRoot.children, we should see that htmlRoot has two children: “head” and “body.”

We already know we want the body, which is the second child. Since our index starts at 0, htmlRoot.children[0] would refer to the head, and htmlRoot.children[1] would refer to the body. Let’s save the body as a new variable. We can do that with var body = htmlRoot.children[1], and pressing enter.

Now let’s look at our body variable:

All the code entered to get here is recapped at the bottom of the page.

Well, I think that’s pretty neat. We now have a JavaScript variable that represents the HTML “body” element. Now to get that first paragraph, we need to go to the first child of the body, which is a “div” and then the second child of that div would be our paragraph (p element). That will be:

var firstDiv = body.children[0]
var firstParagraph = firstDiv.children[1]

In the console it would look like:

As you can see, we finally have our paragraph saved as a variable! Now we can manipulate the text, style, class, id, or other attributes of our “p” element. This style of selecting an HTML element by going up or down the tree using children or parent selectors is called “walking the DOM.” There are other ways to select elements on a page, but I will cover these in future posts.

Changing An Element’s Text With JavaScript

Let’s update the text in our first paragraph to say “Hello World.” Even though navigating the DOM and selecting the first paragraph was somewhat complicated, changing the text itself is very easy. The paragraph element, which is of course an object, has a property “innerText.” If we type firstParagraph.innerText, we will see the current text of the element returned.

We can simply set this innerText to our new value and it will update the page.

firstParagraph.innerText = "Hello World"

Instantly, our text gets updated to “Hello World”.

Recap

In order to update a section of text on the screen, the first step we need to take is selecting the element’s DOM object. Then we can reassign the inner text. For this page, it looks like:

What’s next?

There are lots of methods that can be used to select elements from the DOM, and while many of them would have made selecting this element easier, in my opinion it is very important to learn how to navigate the DOM using a simple straight “walk down” as demonstrated here. Learning this method helps provide an understanding of what the DOM is and how it is structured.

In my next post, I plan to go over other “document” methods that will make navigating and manipulating the DOM simpler and faster.

In the meantime, play around with selecting DOM elements and updating them. Share some screenshots in the comments section.