JavaScript Display Possibilities JavaScript can “display” data in different ways: Writing into an HTML element, using innerHTML. Writing into the HTML output using document.write(). Writing into an alert box, using window.alert(). Writing into the browser console, using console.log(). Using innerHTML To access an HTML element, JavaScript can use the document.getElementById(id) method. The id attribute defines the HTML element. The innerHTML property defines the HTML content: Example <!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p>My First Paragraph</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = 5 + 6; </script> </body> </html> Using document.write() For testing purposes, it is convenient to use document.write(): Example <!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p>My first paragraph.</p>…
-
-
Javascript can be placed in three ways. Between <head> and </head> Between <body> and </body> External JS File How To Define Javascript In HTML, JavaScript code must be inserted between <script> and </script> tags. <script> document.getElementById("demo").innerHTML = "My First JavaScript"; </script> Old JavaScript examples may use a type attribute: <script type=”text/javascript”>. The type attribute is not required. JavaScript is the default scripting language in HTML. JavaScript Functions and Events A JavaScript function is a block of JavaScript code, that can be executed when “called” for. For example, a function can be called when an event occurs, like when the user clicks a button. You will learn…
-
One of many JavaScript HTML methods is getElementById(). This example uses the method to “find” an HTML element (with id=”line”) and changes the element content (innerHTML) to “Hello JavaScript”: <html> <body> <h2>Java Script Can Change HTML Content</h2> <p id="line">This Is HTML Content</p> <button type="button" onclick='document.getElementById("line").innerHTML = "The Content Is Changed By Javascript"'>Click Me to Change</button> </body> </html> JavaScript accepts both double and single quotes: JavaScript Can Change HTML Attribute Values In this example JavaScript changes the value of the src (source) attribute of an <img> tag: <html> <body> <h2>Java Script Can Change HTML Attribute</h2> <button type="button" onclick='document.getElementById("bulb").src = "off.gif"'>Off The…