Javascript - Getting Started (Hello World) in the browser

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript)

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

3 - Code Execution

3.1 - Console

You can run Javascript directly from the Browser Console

3.2 - 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
index.html
<html>
<body>
<!--- The HTML --->
<script src="lib.js" type="application/javascript"></script>
</body>
</html>
  • The Javascript file
lib.js
// javascript code
Advertising

4 - Hello World

4.1 - Modifying the text of an HTML element

Example: Adding Hello to the text of an H1 element

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

4.2 - 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
lib.js
var div = document.createElement("h1");
div.innerHTML = "Hello, world!";
  • Adding it to the DOM body.
lib.js
document.body.appendChild(div);
  • The body of the page is empty
index.html
<!-- Empty body -->
  • Result

Advertising

5 - Documentation / Reference