JavaScript Introduction

JavaScript is the programming language of HTML and the Web.

JavaScript is easy to learn.

This tutorial will teach you JavaScript from basic to advance.

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”:

JavaScript accepts both double and single quotes

document.getElementById(‘demo’).innerHTML = ‘Hello JavaScript’;

document.getElementById(“demo”).innerHTML = “Hello JavaScript”;

<!DOCTYPE html>
<html>
<body>
<h2>Javascript Test Run</h2>
<p id="demo">JavaScript can change HTML content</p>
<button type="button" onclick='document.getElementById("demo").innerHTML = "Hello JavaScript!"'>Click Me!</button>
</body>
</html>

JavaScript Can Change HTML Attribute Values

In this example JavaScript changes the value of the src (source) attribute of an <img> tag:

<!DOCTYPE html>
<html>
<body>
<h2> Javascript Test Run </h2>
<p>JavaScript can change HTML attribute values.</p>
<p>In this case JavaScript changes the value of the src (source) attribute of an image.</p>
<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>
<img id="myImage" src="pic_bulboff.gif" style="width:100px">
<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>
</body>
</html>

JavaScript Can Change HTML Styles (CSS)

<!DOCTYPE html>
<html>
<body>
<h2> Javascript Test Run </h2>
<p id="demo">JavaScript can change the style of an HTML element.</p>
<button type="button" onclick="document.getElementById('demo').style.fontSize='35px'">Click Me!</button>
</body>
</html>

JavaScript Can Hide HTML Elements

Hiding HTML elements can be done by changing the display style:

<!DOCTYPE html>
<html>
<body>
<h2> Javascript Test Run </h2>
<p id="demo">JavaScript can hide HTML elements.</p>
<button type="button" onclick="document.getElementById('demo').style.display='none'">Click Me!</button>
</body>
</html>

JavaScript Can Show HTML Elements

Showing hidden HTML elements can also be done by changing the display style:

<!DOCTYPE html>
<html>
<body>
<h2> Javascript Test Run </h2>
<p>JavaScript can show hidden HTML elements.</p>
<p id="demo" style="display:none">Hello JavaScript!</p>
<button type="button" onclick="document.getElementById('demo').style.display='block'">Click Me!</button>
</body>
</html>

The <script> Tag

In HTML, JavaScript code must be inserted between <script> and </script> tags.

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript in Body</h2>
<p id="demo"></p>
<script>
   document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
</body>
</html>