Document and elements

Introduction

JavaScript is used to create interactive web pages. It can be used to change the content of the page, change the style of the page, and respond to user actions.

Document is the root of the HTML document. It is used to access the elements of the HTML document.

Example:
<html>
  <head>
    <title>Title</title>
  </head>
  <body>
    <h1>Heading</h1>
    <p id="para">Paragraph</p>
  </body>
</html>

To access the document:
document.title
document.body.firstChild
document.getElementById("para")

Getting value of element

To get the value of an element, use the innerHTML property.

<div id="txt">Text</div>

To get the value of the element:
document.getElementById("txt").innerHTML

Get value from document element:
<div id="txt">Text</div>
<button onclick="getValue()">Get value</button>
<script>
  function getValue() {
    alert(document.getElementById("txt").innerHTML);
  }
</script>

Get value from input field:
<input type="text" id="txt">
<button onclick="getValue()">Get value</button>
<script>
  function getValue() {
    alert(document.getElementById("txt").value);
  }
</script>

Set value to element:
<div id="txt">Text</div>
<button onclick="setValue()">Set value</button>
<script>
  function setValue() {
    document.getElementById("txt").innerHTML = "New text";
  }
</script>

Task

Create a web page with a button and a div element.
When the button is clicked, increase the value in the div element by 1.
01 02 03

Reference

Document.getElementById()