JavaScript is the world’s most popular programming language.
JavaScript is the programming language of the Web.
JavaScript is easy to learn.
This tutorial will teach you JavaScript from basic to advanced.
JavaScript Can Change HTML Content
One of many JavaScript HTML methods is getElementById()
.
The example below “finds” an HTML element (with id=”demo”), and changes the element content (innerHTML) to “Hello JavaScript”:
Example
<!DOCTYPE html> <html> <body> <h2>What Can JavaScript Do?</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>
Result:
Result Is shown in your browser. Copy this code and paste in your editor save is and run the code.
JavaScript accepts both double and single quotes:
Example
<!DOCTYPE html> <html> <body>
<h2>What Can JavaScript Do?</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:
The Light Bulb
<!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='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)
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='35px'">Click Me!</button> </body> </html>
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>
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>