English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JavaScript Basic Tutorial

JavaScript Objects

JavaScript Functions

JS HTML DOM

JS Browser BOM

AJAX Basic Tutorial

JavaScript Reference Manual

Common JavaScript Examples

This page contains some examples of what JavaScript can do.

Note:If some of these examples use methods that you have not learned yet,PleaseDon't worry. You will learn about them in the next chapter.

JavaScript can modify HTML content

The getElementById() method returns the element that matches the specified ID.

In this example, this method is used to find an HTML element (id="para") and change the content of the element (innerHTML) to "Hello world":

document.getElementById("para").innerHTML = "Hello world";
Test and See ‹/›

JavaScript can change the value of HTML attributes

In this example, JavaScript changed<img>of the tagsrcThe value of the property:

Click the button to change the avatar:

JavaScript can change HTML styles (CSS)

JavaScript styleProperties can be used to set the inline style of elements.

document.getElementById("demo").style.color = "blue";
Test and See ‹/›

JavaScript can hide HTML elements

Hiding HTML elements can also be done by changing the display style.

document.getElementById("demo").style.display = "none";
Test and See ‹/›

JavaScript can display HTML elements

Displaying or hiding HTML elements can also be done by changing the display style.

document.getElementById("demo").style.display = "block";
Test and See ‹/›

JavaScript can create alert pop-up windows

In this example, JavaScript creates an alert dialog box.

alert("Hello world!");
Test and See ‹/›

JavaScript can attach event handlers to the document

In this example, JavaScript monitors mouse click events and responds to them.

document.addEventListener("click", myFunc);
function myFunc() {
   document.body.style.backgroundColor = "coral";
}
Test and See ‹/›

JavaScript can display time

In this example, JavaScript displays the current time.

var intervalID = setInterval(startTimer, 1000);
function startTimer() {
    var date = new Date();
    var x = document.getElementById("result");
    x.innerHTML = date.getHours(); + : + date.getMinutes() + : + date.getSeconds();
}
Test and See ‹/›