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")
<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>