What is document.getElementById

Often we need to access element(s) or part(s) on a page to do something with it. For this we can use DOM queries. Depending on the number of elements we need to access, Javascript provides multiple methods to do that. If we need to access only one element, we can use the “getElementById” method. It is a document method and it returns a single element node.

In the HTML document we must have an ID attribute that we can access with the “getElementById” method.

The basic syntax

document.getElementById( id )

Here the “document” refers to the document object. It is followed by the dot notation.

The “getElementById” is the method being used and it tells tat we want to access an element by its ID.

The “id” (parameter of the method) is the value of the id attribute on the HTML page.

Since the same id attribute cannot occur more than once on the same page, getting an element by its id is usually the fastest and most efficient way to access or return it.

Example:

In this example, we have a div with a red background. The div has an id attribute with the value “section. Then we add two buttons with onclick events to change the background color of the div when clicked.

<div id="section" style="width: 100%; height: 300px; background: red; margin-bottom: 15px;">
this is a text inside the section
</div>

<input type="button" onclick="changeBg('blue')" value="Change to blue">
<input type="button" onclick="changeBg('red')" value="Change to red">

In our javascript file we need to create a function to handle the onclick events on the buttons.

function changeBg(newBgCol) {
   const section = document.getElementById('section');
   section.style.backgroundColor = newBgCol;
}

We name the function to “changeBg” and add a parameter called “newBgCol”.

Then inside the function we reference the part of the HTML that we want to change or run an operation on. We use the const keyword to create a variable called “section” which will refer to the div on our HTML.

Then we use the “style” property of Javascript on the section to change the background color. This will equal to whatever color we use in the o’clock event.

External resources:

ChristianKovats
ChristianKovats

Christian Kovats is a London-based web designer who loves crafting innovative and user-friendly interfaces. His passion for design is only rivaled by his love for nature and hiking, often drawing inspiration from his treks through the diverse landscapes of the UK. Outside of work, Christian enjoys spending quality time with his wife and 4-year-old son. A seasoned lucid dreamer, he also spends time exploring the intricate world of dream interpretation, reflecting his ever-curious and creative mind.

ChristianKovats

Leave a reply

You must be logged in to post a comment.