30 Days Of JavaScript

Day 16: DOM Manipulation

Lesson 1: Getting DOM Elements

getElementById()

Add these lines to your script tag area:

1const text = document.getElementById("red-text");
2console.log(text);

Your console will have this printed out:

1<p id="red-text">Hello World</p>

Pretty cool! We used the id red-text to grab a whole HTML element and print it out. Let's see what we can do with this.

Change your console.log to console.log(text.innerHTML);

Now you see just Hello World in you console. Change your HTML to this:

1<div id="container">
2  <p id="red-text">Hello World</p>
3</div>

and your JavaScript to:

1const container = document.getElementById("container");
2console.log(container);
3console.log(container.innerHTML);

This time you can see how getting an element also gets all the other elements in side it, you should also be able to see how to console treats the output of just logging the element and the innerHTML. The first is an HTMLElement and the second is just a string of the HTML inside that HTMLElement.

All HTML tags have attributes on them, every time you write id="container" or type="text" you are setting an attribute. You can get the attribute of any element like this:

Change your HTML to this:

1<div class="title-large" id="container">
2  <p id="red-text">Hello World</p>
3</div>

and your JavaScript to this:

1const container = document.getElementById("container");
2
3const attributes = container.attributes;
4
5console.log(attributes);
6
7for (const attr of attributes) {
8  console.log(`${attr.name} -> ${attr.value}`);
9}

You can see here that we were able to get the element and print out it's attributes in two ways. The first was a simple console.log which dumped out way more information about each element that you probably expected (remember to click the little arrow to the left of the line to expand the full map) and then the second, where we simply looped through the map of attributes and printed the name and value.

getElementsByClassName()

Change your HTML to this:

1<div class="title-large" id="container">
2  <p class="title-small">Hello Simon</p>
3  <p class="title-small">Hello Raj</p>
4  <p class="title-small">Hello Zuma</p>
5  <p class="title-small">Hello Sara</p>
6</div>

and JavaScript to this:

1const titles = document.getElementsByClassName("title-small");
2console.log(titles);

Our console.log has printed out an HTMLCollection, which is every element on the page that has the class title-small. If you want to access a single one, like the first, then you can do this:

1console.log(titles[0]);

and now we are back to having an HTML element like before.

Or you can loop through them all:

1for (const title of titles) {
2  console.log(title.innerHTML);
3}

Now we have access to our HTML elements, what can we do with them? Let's take a look!

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co