Introduction - JavaScript

 
1. 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":

 

<!DOCTYPE html>

<html>

<body>

 

<h2>JavaScript can change HTML content.</h2>

 

<p id="demo">Change HTML content.</p>

 

<button type="button" onclick='document.getElementById("demo").innerHTML = "Hello JavaScript!"'>Click Me!</button>

 

</body>

</html>

 

JavaScript accepts both double and single quotes:

 

<!DOCTYPE html>

<html>

<body>

 

<h2>JavaScript can change HTML content.</h2>

 

<p id="demo">Change HTML content.</p>

 

<button type="button" onclick="document.getElementById('demo').innerHTML = 'Hello JavaScript!'">Click Me!</button>

 

</body>

</html>

 

2. 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>What Can JavaScript Do?</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='light_on.gif'">Turn on the light</button>

 

<img id="myImage" src="light_on.gif" style="width:100px">

 

<button onclick="document.getElementById('myImage').src='light_off.gif'">Turn off the light</button>

 

</body>

</html>

 

- light_on.gif

- light_off.gif

 

3. JavaScript Can Change HTML Styles (CSS)

Changing the style of an HTML element, is a variant of changing an HTML attribute:

Example

 

<!DOCTYPE html>

<html>

<body>

 

<h2>What Can JavaScript Do?</h2>

 

<p id="demo">JavaScript can change the style of an HTML element.</p>

 

<button type="button" onclick="document.getElementById('demo').style.fontSize='30px'">Click Me!</button>

 

</body>

</html>

 

4. JavaScript Can Hide HTML Elements

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

Example

 

<!DOCTYPE html>

<html>

<body>

 

<h2>What Can JavaScript Do?</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>

 

5. JavaScript Can Show HTML Elements

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

Example

 

<!DOCTYPE html>

<html>

<body>

 

<h2>What Can JavaScript Do?</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>