Javascript - Getting Started (Hello World) in the browser

About

Javascript in the browser getting started page.

In a web page, Javascript is modifying the HTML dom (the browser representation of the HTML page).

With the Web Dom API, you handle one DOM element at a time but with processor libraries such as D3, jQuery, you instead handle groups of related elements.

Code Execution

Console

You can run Javascript directly from the Browser Console

Page

In a HTML page, JavaScript can be found:

Javascript code is executed in order of appearance

If the Javascript code is supposed to affect the [web:dom:body|body of the DOM (ie the body of an HTML page)]], it should then be placed after the element that should be modified (generally the script is placed before the end of the body)

Example:

  • File Structure
index.html
lib.js

  • The HTML page
<html>
<body>
<!--- The HTML --->
<script src="lib.js" type="application/javascript"></script>
</body>
</html>
  • The Javascript file
// javascript code

Hello World

Modifying the text of an HTML element

Example: Adding Hello to the text of an H1 element

var myHeading = document.querySelector("h1");
  • We had the term Hello to the content of the H1 element
myHeading.textContent = "Hello "+myHeading.textContent+"!";
  • The page
<h1>World</h1>
  • And we got as result a modified index.html page

Adding an HTML element to the page

With the DOM append method, we can add an element.

Example: Adding an H1 element

  • Creating the element
var div = document.createElement("h1");
div.innerHTML = "Hello, world!";
  • Adding it to the DOM body.
document.body.appendChild(div);
  • The body of the page is empty
<!-- Empty body -->
  • Result

Documentation / Reference







Share this page:
Follow us:
Task Runner