This is where JavaScript really starts to get fun. In this post, I’m going to go over exactly how to use JavaScript methods to access, change and create elements. If you’re a beginner in JavaScript, I suggest you simply read and absorb. After that, head out into the world of the internet and look up everything you can on the topics I cover below. Learning JavaScript is mostly about exposure – the more you can get, the more comfortable you’ll become with what the language is. Let’s get going.
Accessing DOM Elements
In this section, I’m going to cover a few methods to access elements in the DOM.
getElementById() Method
By using the getElementById() method, you are able to access an element that has a unique ID in the HTML code of a web page. This is probably the most common method of accessing and manipulating elements in JavaScript.
Below, I’ll give some examples of how this works. Beneath the code, I’ll explain what’s going on.
document.getElementById(elementID)
This is the standard syntax for this method. As you can see in the above code, you are accessing the document first, then searching for a general element by an ID and then specifying the actual element itself. It’s sort of like a chain – you need to start at the beginning.
In order to understand how this works, I’ll give a short example of some HTML:
<!DOCTYPE html> <html> <head> <title>Example Page</title> </head> <body> <p id="firstParagraph">This is the content of my first paragraph.</p> </body> </html>
Now, I’ll write some JavaScript:
var firstParagraphText = document.getElementById("firstParagraph");
By writing this JavaScript code, I have accessed the p element in my HTML code and set it to the variable, “firstParagraphText.” If I wanted to display just the text within the element (in between the element tags), I would need to use the innerHTML property. I’ll talk more about the innerHTML property in later posts. For now, just remember that the innerHTML property sets or returns the HTML content of an element.
Let’s look at some code.
<!DOCTYPE html> <html> <head> <title>Example Page</title> </head> <body> <p id="firstParagraph">This is the content of my first paragraph.</p> <script> var firstParagraphText = document.getElementById("firstParagraph"); console.log(firstParagraphText); </script> </body> </html>
If I run this code in a browser and looked at the console, I’d see the following:
<p id="firstParagraph">This is the content of my first paragraph.</p>
The reason I’m seeing the entire element is because that’s what I accessed by using the getElementById() method in JavaScript. If I wanted only the text in between the tags, like I mentioned above, I would need to take advantage of the innerHTML property.
<!DOCTYPE html> <html> <head> <title>Example Page</title> </head> <body> <p id="firstParagraph">This is the content of my first paragraph.</p> <script> var firstParagraphText = document.getElementById("firstParagraph"); console.log(firstParagraphText.innerHTML); </script> </body> </html>
If you’ll notice in the code above, I added the innerHTML right after the variable, “firstParagraphText” in the second line of the script. Now, the output in the console is just the text:
This is the content of my first paragraph.
Just a quick note – if no elements with the ID I’m looking for exist on the page, I’ll get null as the output. Also, if more than one element with a particular ID exists on the page, the first element will be the output. Further elements will be ignored.
getElementsByTagName() Method
Let’s say I updated my code to include a second paragraph and an unordered list and I wanted to access elements on my page by tag name, instead of by ID. The syntax I would need to use would look like this:
document.getElementsByTagName(tagname)
The code I would need to use would look like this:
<!DOCTYPE html> <html> <head> <title>Example Page</title> </head> <body> <p id="firstParagraph">This is the content of my first paragraph.</p> <p id="secondParagraph">This is the content of my second paragraph.</p> <ul> <li>First list item</li> <li>Second list item</li> <li>Third list item</li> </ul> <script> var paragraphElements = document.getElementsByTagName("p"); var listItemElements = document.getElementsByTagName("li"); console.log(paragraphElements.length); console.log(listItemElements.length); </script> </body> </html>
In the above code, you can see my two paragraphs and the list I created. Below those elements, I wrote some code. In the first two lines of code, I accessed two types of elements by tag name and set them to variables. By doing this, I created two arrays in the computer’s memory. Those arrays are going to be filled with as many of those types of elements that are on the page. It doesn’t matter how many there are – if they are the same type of element, they’ll be captured.
In the next two lines of code, I output the length of each array in the console. In this case, the output is:
2
3
Let’s have a little fun. Since we can access our arrays (the above variables) by index, we can output the inner HTML of whichever element we want. Take a look at this code:
<!DOCTYPE html> <html> <head> <title>Example Page</title> </head> <body> <p id="firstParagraph">This is the content of my first paragraph.</p> <p id="secondParagraph">This is the content of my second paragraph.</p> <ul> <li>First list item</li> <li>Second list item</li> <li>Third list item</li> </ul> <script> var paragraphElements = document.getElementsByTagName("p"); var listItemElements = document.getElementsByTagName("li"); console.log(paragraphElements[0].innerHTML); console.log(listItemElements[1].innerHTML); </script> </body> </html>
Notice how I changed the console.log statements. Now, I’m accessing the first element (the 0 index) of the paragraphElements array and the second element (the 1 index) of the listItemElements array. In these statements, I’m only looking to output the text that’s in the elements, in between the tags. For this, I again use the innerHTML property. The output looks like this:
This is the content of my first paragraph.
Second list item
How cool is that?
Retrieving Only Certain Elements
We have a little problem. In the last code example I gave, the getElementsByTagName() method accessed all elements of a tag name. What if we only wanted to access certain elements of a tag name? What if we had two unordered lists and we only wanted to access one? Take a look at the following code:
<!DOCTYPE html> <html> <head> <title>Example Page</title> </head> <body> <ul id="firstList"> <li>First list item</li> <li>Second list item</li> <li>Third list item</li> </ul> <ul id="secondList"> <li>Fourth list item</li> <li>Fifth list item</li> <li>Sixth list item</li> </ul> <script> var listItemElements = document.getElementsByTagName("li"); console.log(listItemElements.length); </script> </body> </html>
If I were to run this page and look at the output in the console, I’d see “6.” That’s the length of the array I created. If we wanted to access the first list only, we’d have to modify the script code to look like this:
<!DOCTYPE html> <html> <head> <title>Example Page</title> </head> <body> <ul id="firstList"> <li>First list item</li> <li>Second list item</li> <li>Third list item</li> </ul> <ul id="secondList"> <li>Fourth list item</li> <li>Fifth list item</li> <li>Sixth list item</li> </ul> <script> var firstListElements = document.getElementById("firstList"); var listItemElements = firstListElements.getElementsByTagName("li"); console.log(listItemElements.length); </script> </body> </html>
Since I want to limit my access to just one unordered list, I can’t begin my search at the document level. I need to create a new “search zone” of limited scope. To do this, I accessed the list with the ID of “firstList” and set that to a variable named, “firstListElements.” After that, I used the getElementsByTagName() method again, but this time, I didn’t begin with “document.” I began with my newly created zone of “firstListElements.” I continued as I normally would and my output was now:
3
That’s how you can refine a blunt instrument and narrow your HTML to get your desired output.
Changing DOM Elements
The first step in changing an element is to get the element. In the last section, we accessed the elements in question, so that’s done. In this section, I’m going to write some code that will show you how to change an element. I’m going to start off really easy and simply continue on using my very last example. Let’s look at some code:
<!DOCTYPE html> <html> <head> <title>Example Page</title> </head> <body> <ul id="firstList"> <li>First list item</li> <li>Second list item</li> <li>Third list item</li> </ul> <ul id="secondList"> <li>Fourth list item</li> <li>Fifth list item</li> <li>Sixth list item</li> </ul> <script> var firstListElements = document.getElementById("firstList"); var listItemElements = firstListElements.getElementsByTagName("li"); listItemElements[2].innerHTML = "<strong>This list item has been CHANGED!!!</strong>"; </script> </body> </html>
Can you guess what the output of this page would be? Here, take a look:
First list item
Second list item
This list item has been CHANGED!!!
Fourth list item
Fifth list item
Sixth list item
Okay, so here’s what happened. Just like last time, I accessed the firstList ID in the first list and set that to a variable named firstListElements. Then, I accessed the li elements only in the first list and stored them in a variable called listItemElements. After that, I changed the third list item (index number 2) inner HTML, or text, to output “This list item has been CHANGED!!!” in bold. As you can see, if you’ve done all the work to get the element or ID, it’s not too difficult to change something about it. Let’s look at some more examples.
Say we wanted to change the alignment of an specific area of a page. We could do that. Take a look at this code:
<!DOCTYPE html> <html> <head> <title>Example Page</title> </head> <body> <div id="mainContent"> <h1>This is the Main Title</h1> <p>This is the main paragraph.</p> </div> <script> var mainContent = document.getElementById("mainContent"); mainContent.setAttribute("align", "right"); </script> </body> </html>
In the above example, I used the setAttribute() Method. That method looks like this:
element.setAttribute(name, value);
It’s defined as, “Adds a new attribute or changes the value of an existing attribute on the specified element.”
Now knowing this, we can go through the above example. In this code, I added an h1 element and a p element. In both spaces, I typed in some filler text. In the script area, I used the getElementById() method to access the id, “mainContent” in the div element. I stored that data in a variable called “mainContent.” After that, I set the align attribute of the variable I created (the mainContent ID in the dev element) to right. Now, both the h1 and the p elements are aligned to the right.
Here’s another one for you. Say we had a style set in the head area of our page and we wanted to apply the style to a particular element in our page. In the code below, I created a style, but by default, it isn’t connected to anything. If we use a little JavaScript, we can change that. Take a look:
<!DOCTYPE html> <html> <head> <title>Example Page</title> <style> .red-class { color: red; } </style> </head> <body> <div id="mainContent"> <h1>This is the Main Title</h1> <p>This is the main paragraph.</p> </div> <script> document.getElementsByTagName("h1")[0].setAttribute("class", "red-class"); </script> </body> </html>
What I did above was to get the h1 element (the first one in the array with the index of 0) and then I created a class for it named “red-class.” Now, when the page is loaded, any text within the h1 element will be red because the h1 element is now connected to the style I created in the head section. What wasn’t before, now is.
If I wanted to go one step further and actually change the text that’s between the h1 tags, I can do that:
<!DOCTYPE html> <html> <head> <title>Example Page</title> <style> .red-class { color: red; } </style> </head> <body> <div id="mainContent"> <h1>This is the Main Title</h1> <p>This is the main paragraph.</p> </div> <script> document.getElementsByTagName("h1")[0].setAttribute("class", "red-class"); document.getElementsByTagName("h1")[0].innerHTML = "This is the NEW Main Title!!!"; </script> </body> </html>
By adding the line:
document.getElementsByTagName("h1")[0].innerHTML = "This is the NEW Main Title!!!";
I changed the inner HTML of the h1 element. Now, this new line of text appears in the place of the original text.
Creating DOM Elements
This area of JavaScript is very exciting. It’s actually sort of empowering. When you’re finished reading what I write below, I’m sure you’ll say what I said – “Wow, that’s really cool!”
I’m going to attempt to explain the whole idea of creating elements with JavaScript as clearly as I can. If I miss anything, please let me know in the comment section below. All right – let’s go.
There are a few ways to create elements with JavaScript and “insert” them into a web page. I’ll go over each method that I currently know of below.
There are always two steps we need to take when we want to dynamically insert something into a page:
1. Create the element.
2. Add the element to the document.
Just keep those two things in mind and it’ll help a lot.
Let’s start off with a code example:
<!DOCTYPE html> <html> <head> <title>Jay's Example Page</title> </head> <body> <div id="mainContent"> <h1>This is the Main Title</h1> <p>This is the main paragraph.</p> </div> <ul id="listContent"> <li>First list item</li> <li>Second list item</li> <li>Third list item</li> </ul> <script> var myNewElement = document.createElement("li"); myNewElement.innerHTML = "Fourth list item"; document.getElementById("listContent").appendChild(myNewElement); </script> </body> </html>
This one is pretty simple. The goal with the JavaScript code above is to add a fourth list item to the current list of three items. My unordered list has an ID of listContent and each list item has no ID.
If we look at the JavaScript code above, we can see that I wrote three lines of code.
In the first line, I used the createElement() method to create a new li element and stored that element in a variable called myNewElement.
In the second line, I used the innerHTML property to add text within the li element. In this case, the text says, “Fourth list item.”
Finally, in the last line, I used the getElementById() method to get the unordered list I’d like to add the new list item to. After that, I used the appendChild() method to add my new list item to the bottom of the current list.
There you have it – a fourth item in the list. Once you get the hang of it, it’s really not too painful.
Now, there is another way of adding content to the list item, besides using the innerHTML property. We could create an actual text node and add that to our element. Here, look at some more code:
<!DOCTYPE html> <html> <head> <title>Jay's Example Page</title> </head> <body> <div id="mainContent"> <h1>This is the Main Title</h1> <p>This is the main paragraph.</p> </div> <ul id="listContent"> <li>First list item</li> <li>Second list item</li> <li>Third list item</li> </ul> <script> // create new element var myNewElement = document.createElement("li"); // create text node var listText = document.createTextNode("Fourth list item"); // add text node to new element myNewElement.appendChild(listText); // attach new element to the document document.getElementById("listContent").appendChild(myNewElement); </script> </body> </html>
This one should be a bit easier to follow because I added some comments. I think I’m going to do this from now on. Not only does it help you, it helps me as well.
We already know what happened on the first line. We created the new element. On the second line, instead of using the innerHTML property to add the text to the element, we took advantage of the createTextNode() method to create our filler text. On the third line, we put our element and text node together and finally, just like last time, we used the getElementById() method to get the element we want to add our list item to and appended our new element to it.
I actually like this way better because it’s easier on the head. It keeps the steps broken up more.
Here’s a question – What if we want to add our new list item someplace other than at the end of our list? What if we want to add it to the first spot in the list and push the other list items down a spot? Well, we can do that. Take a look at this updated code:
<!DOCTYPE html> <html> <head> <title>Jay's Example Page</title> </head> <body> <div id="mainContent"> <h1>This is the Main Title</h1> <p>This is the main paragraph.</p> </div> <ul id="listContent"> <li>First list item</li> <li>Second list item</li> <li>Third list item</li> </ul> <script> // create new element var myNewElement = document.createElement("li"); // create text node var listText = document.createTextNode("Fourth list item"); // add text node to new element myNewElement.appendChild(listText); // get the list var newList = document.getElementById("listContent"); // insert new list item newList.insertBefore(myNewElement, newList.childNodes[0]); </script> </body> </html>
In the above code, I removed the last line from the previous example and replaced it with two new lines. In the fourth line now, I used the getElementById() method to get the list we want to add the new list item to and stored that in a variable named newList. In the last line, I used the insertBefore() method to define exactly where I wanted to place the new list item. I also used the childNodes property to return the child nodes of the unordered list with the ID of listContent. I also specified which position I’d like to insert the new list item before. In this case, I chose the first list item, or the one with the index of 0.
Well, that’s it for this post. If you’re interested in more JavaScript tutorials, please keep your eye on my JavaScript category. I’m constantly adding more fun filled posts.
Leave a Reply