Author: MDBootstrap
In this lesson, you will see some simple examples of what JavaScript can do.
Note: Do not worry if you do not understand how this code works exactly. These are just demonstrative examples illustrating the capabilities of JavaScript. Everything will be explained in detail in the next lessons.
JavaScript Can Change HTML Content
One of many JavaScript HTML methods is getElementById().
This example uses the method to "find" an HTML element (with id="demo") and changes the element content (innerHTML) to "Hello JavaScript":
<p id="example-1">JavaScript can change HTML content.</p>
<button type="button" onclick='document.getElementById("example-1").innerHTML = "Hello JavaScript!"'>Click Me!</button>
Live preview
JavaScript can change HTML content.
Note: JavaScript accepts both double ( " ) and single ( ' ) quotes:
document.getElementById('demo').innerHTML = 'Hello JavaScript';
JavaScript Can Change HTML Attribute Values
In this example JavaScript changes the value of the src (source) attribute of an tag. Click the
buttons to see the effect:
<button onclick="document.getElementById('myImage').src='https://mdbootstrap.com/img/Photos/Avatars/img%20(20).webp'">Girl</button>
<img id="myImage" src="https://mdbootstrap.com/img/Photos/Avatars/img%20(20).webp" style="width:100px">
<button onclick="document.getElementById('myImage').src='https://mdbootstrap.com/img/Photos/Avatars/img%20(3).webp'">Boy</button>
Live preview
.webp)
JavaScript Can Change HTML Styles (CSS)
Changing the style of an HTML element, is a variant of changing an HTML attribute:
<p id="example-3">I will become bigger!</p>
<button type="button" onclick="document.getElementById('example-3').style.fontSize='35px'">Click Me!</button>
Live preview
I will become bigger!
JavaScript Can Hide HTML Elements
Hiding HTML elements can be done by changing the display style:
<p id="example-4">I will disappear!</p>
<button type="button" onclick="document.getElementById('example-4').style.display='none'">Click Me!</button>
Live preview
I will disappear!
JavaScript Can Show HTML Elements
Showing hidden HTML elements can also be done by changing the display style:
<p id="example-5" style="display:none">Hello JavaScript!</p>
<button type="button" onclick="document.getElementById('example-5').style.display='block'">Click Me!</button>
Live preview
Note: Of course, these are just a few very basic examples. JavaScript is a powerful technology and its capabilities are enormous. You will learn its full potential step by step.
Previous lesson Next lesson
Spread the word: