CommonLounge Archive

JavaScript: Interacting with HTML Elements

September 26, 2018

So far in this course, we’ve been using JavaScript to perform some operations and print results on the screen. But, that’s not all JavaScript is good for. JavaScript is primarily used for making HTML pages interactive. In this and the coming tutorials we will be learning about using JavaScript with HTML elements.

This tutorial assumes that you have some knowledge of HTML. If you don’t, do not worry. The first section covers enough HTML for you to be able to understand this tutorial.

Quick intro to HTML

<html>
    <head>
        <title> Title of the page </title>
    </head>
    <body>
        Content
        More content...
    </body>
</html>

This is what a typical HTML page looks like in structure. HTML has tags that define a certain object. Most tags have an opening and a closing tag. A closing tag is differentiated with a forward slash / just after the opening angular bracket (for example, </body> is a closing tag).

The top-level tag in an HTML file is the <html> tag itself. Usually, within this tag, we have:

  • The <head> tag which contains HTML elements which define the title of the webpage, and also includes any CSS styles, JavaScript, links to external files, and optionally some meta information about the page. In our example above, it only has the <title> tag. When this HTML is opened on a browser, the title is displayed on the title bar of the browser window.
  • The <body> tag, which is where all the main goes. Anything that is not enclosed in angular brackets < and > is not a tag and gets displayed on the HTML page.

To add JavaScript code to a HTML file, we must enclose it in the <script> tag.

All tags in HTML have attributes associated to them. For e.g., the <script> tag has an attribute type which can be used to specify the type of script enclosed within the tag.

If you’d like to learn HTML in more depth, check out Getting Started with HTML and CSS tutorial from the Learn HTML & CSS course.

Let’s make a new HTML file called "intro.html". Copy-paste the following code into this new file.

<html>
    <head>
        <title>Introduction</title>
    </head>
    <body style="background: LightGreen;">
        <b style="font-size: 40px;">
            Hello World!
        </b>
        <p>
            Random sentences with no meaning coming up... <br>
            Attention he extremity unwilling on otherwise. 
            Conviction up partiality as delightful is discovered. <br>
            <i> Fin </i>
        </p>
    </body>
</html>

Enclosing text inside <b> and </b> tags makes the enclosed text bold. Similarly, <i> tag is used for italics and <u> is used for underline. The <br> tag is used to go to a new line (stands for break).

In addition, in the above HTML we have used the style attribute in both the <body> tag and the <b> tag. Many attributes — such as style, id, class — are common to all HTML tags. The style attribute is used to specify styles for the current element. For the <body> tag we have specified the background to LightGreen, and for the <b> tag the font-size to 40 pixels. These styles are specified in the format attribute: value;.

To learn more about styling HTML using CSS (Cascading Style Sheets) see Getting Started with HTML and CSS tutorial from the Learn HTML & CSS course.

If you open this page in a browser you should see a window with LightGreen background, a big “Hello World!” written in black and a paragraph of random words with no meaning. Something like this:

Screenshot of the HTML page. (Click to enlarge)

HTML DOM

When a web page is loaded, the browser creates a DOM (Document Object Model). The DOM is basically a representation of the HTML elements in the form of a tree, in which the root denotes the <html> tag and all other tags are its descendants. So the HTML code we saw earlier can be represented as

            html
           /    \
        head    body
        /       /  \
     title     b    p
                  / |  \ 
                br  br  i

id, class and name attributes

Every HTML tag can have the id, class and name attributes. The id attribute is generally used as a unique id for identifying an HTML element, the class attribute is used to specify multiple items with similar properties and name is usually used as an identifier for HTML form elements (which you will see in detail after a couple of tutorials).

Let’s see an example HTML with id, class and name attributes:

<html>
  <body>
    <p id="ptag">
        This is a paragraph with id ptag.
    </p>
    <p class="pclass">
        This is a paragraph with class pclass.
    </p>
    <p name="pname">
        This is a paragraph with name pnam.
    </p>
  </body>
</html>

Accessing HTML elements from JavaScript

The document object gives access to the HTML DOM from JavaScript. The object also has different methods which can be used to access HTML elements using their id, class and name attributes. There’s also a method which can be used to access elements using tag names. Let’s look at how we can get references to HTML elements using these methods.

Let’s see some examples. Save the following as elements.html and open it in your browser.

<html>
 <body>
   <p id="ptag">
        This is a paragraph with id ptag.
   </p>
   <p class="pclass">
        This is a paragraph with class pclass.
   </p>
   <p name="pname">
        This is a paragraph with name pnam.
   </p>
   <script>
    // reference to the first element with id "ptag" i.e. the first <p> tag
    var paragraphFromId = document.getElementById("ptag");
    // array of elements which have the given class
    var allFromClass = document.getElementsByClassName("pclass");
    // if we want the first paragraph, when we need to
    // get the first element (0th index) of the array
    // i.e. this gives the reference to the second <p> tag
    var paragraphFromClass = document.getElementsByClassName("pclass")[0];
    // array of elements with the given name
    var allFromName = document.getElementsByName("pname");
    // reference to the third <p> tag 
    // (same logic as for getElementsByClassName)
    var paragraphFromName = document.getElementsByName("pname")[0];
    // array of elements of the specific tag
    // returns as array of length 3 because there are 3
    // p tag elements in our HTML
    var allptags = document.getElementsByTagName("p");
  </script>
 </body>  
</html>

Play around with these functions in the JavaScript Console in the browser. If you open the above as a HTML in the browser, you can also see the values of the variables themselves by typing paragraphFromId, allptags, etc.

Changing attributes, styles and text using JavaScript

Once we have the reference to an HTML element, we can change its attributes and set values using JavaScript. How about changing the page’s background color using JavaScript?

Change the intro.html file to the following (we added a couple of id attributes, and an image as well):

<html>
    <head>
        <title>Introduction</title>
    </head>
    <body style="background: LightGreen;">
        <b style="font-size: 40px;" id="heading">
            Hello World!
        </b>
        <p id="paragraph">
            Random sentences with no meaning coming up... <br>
            Attention he extremity unwilling on otherwise.
            Conviction up partiality as delightful is discovered.
            Yet jennings resolved disposed exertion you off.
            Left did fond drew fat head poor. <br>
            <i> Fin </i>
        </p>
        <img id="image" width=400 src="https://upload.wikimedia.org/wikipedia/commons/d/db/BradPittBAR08.jpg">
        </img>
    </body>
</html>

Then open it in your browser. You’ll see something like this:

Then open the Console, and type:

> var image = document.getElementById("image");
< undefined
> image.width = 250;
< 250

You will see the image size reduce, from a width of 400px to 250px.

Now, let’s change the image source! Type in:

> image.src = "https://upload.wikimedia.org/wikipedia/commons/8/8d/George_Clooney_2016.jpg";
< "https://upload.wikimedia.org/wikipedia/commons/8/8d/George_Clooney_2016.jpg"

Pretty cool, right? We first got a reference to the image HTML element. Then, we changed its width attribute, and the src attribute.

The same way we changed attributes, we can also update the style or text of any part of the HTML. Here are a few examples.

Next, let’s change the background color to beige.

> var bodytag = document.body;
< undefined
> bodytag.style.background = "Beige";
< "Beige"


And the font-size of “Hello World!” to 100px.

> var hello_world = document.getElementById("heading");
< undefined
> hello_world.style.fontSize = 100;
< 100

Easy, right?

How about changing the text? Let’s change the text in italics (at the end of the paragraph) to “The image below is George Clooney!“.

> var italics = document.getElementsByTagName("i")[0];
< undefined
> italics.innerText = "The image below is George Clooney!";
> "The image below is George Clooney!"

Notice that we used the getElementsByTagName() function this time since we didn’t have an id attribute for the <i> tag. Also, to change the text, we updated the innerText property of the JavaScript object.


There’s a similar property called innerHTML, incase the value you are assigning includes HTML tags. For example, suppose we wanted George Clooney to be bold.

> italics.innerHTML = "The image below is <b>George Clooney<b>!";
< "The image below is <b>George Clooney<b>!"

Alright, let’s move on!

Creating new HTML elements using JavaScript

Now, we will see how to create new HTML elements using JavaScript. Let’s create a new button on the page.

First, we need to create a new button element and give appropriate values to its attributes. Then, we will add it as the last HTML element in the DOM <body>.

// Create a new button element
var btn = document.createElement("button");
// Give some value to the button text
btn.innerText = "Click me!";
// Add element to end of <body>
bodytag.appendChild(btn);
// Output - <button>​Click me!​</button>​

Oops, the button ended up next to the image instead of below it. We need a <br> tag in between. Let’s do it:

bodytag.insertBefore(document.createElement("br"), btn);

Awesome! In general, the syntax of insertBefore() is:

parentNode.insertBefore(newNode, childNode);

Note: The button doesn’t do anything if you click on it. But that’s the topic of the next tutorial!


We’ve covered most of the important functions for accessing and manipulating the DOM using JavaScript, but playing around in the console is a good way of explore other things you can do. The console autocomplete really helps.

Exercise

Create a paragraph below the image. It should say, “Image Source: George Clooney’s wikipedia page”. Make sure “George Clooney’s wikipedia page” is actually a link to the Wikipedia page.

Conclusion

In this tutorial:

  • You learnt how to access HTML elements using their id, class, name attributes and also by tag names.
  • You saw how to change attributes, style and text of HTML elements.
  • And finally, how to create completely new HTML elements dynamically.

Time for a Quiz!


© 2016-2022. All rights reserved.