Using getElementById in Javascript

Seven part section: 1 2 3 4 5 6 7

The document method getElementById is used to manipulate particular HTML elements on your page. As its name suggests, though, the HTML element needs an ID attached to it. As an example, take a look at this segment of a web page:

So we have a textbox and a button. When the button is clicked, we want to make sure that the textbox has been filled in. If it's still blank then we don't want to send the form anywhere. We can keep the user on the same page and colour the textbox, say, red. This will offer a visual clue that the textbox needs to be filled in. Here's what the textbox will look like if it's left blank and the button is clicked:

The code for all this makes use of getElementById. Here it is:

Use of getElementById in Javascript

In the BODY section of the HTML we have a textbox and a button. But notice the highlighted ID for the textbox:

ID="textbox_1"

So we've attached an ID to this HTML element. We then use this ID with the following: (Don't worry about the IF Statement - you'll study those soon.)

if ( document.getElementById("textbox_1").value=='' ) {

}

The getElementById method needs a pair of round brackets. In between these round brackets you type the ID you're trying to access. The ID needs to be surrounded by quote marks, single or double. Textboxes have a VALUE attribute. You can get at this value by adding it after the round brackets (type a dot first, though). We then have two equal symbols. To specify a blank value in the text box, we have two single quote marks (we could have used doubles, though).

One thing to be aware of for getElementById is that the "d" of "Id" is lowercase but the "I" is uppercase. So it's not "ID" but "Id". Get that bit wrong and your code won't work.

To change the textbox red, our code is this:

document.getElementById("textbox_1").style.backgroundColor='red';

So we are still accessing the ID of the textbox. This time, we're adding a style after the round brackets:

.style.backgroundColor='red'

The particular style we're changing is the background colour.

In the next lesson, we'll take a look at the email function of our form. It uses getElementById to display error message.