Since JavaScript has become an integrated part of the Front End Development, you must learn how to read from and write to an HTML document.
Before we go the actual coding, let us have a brief discussion on DOM - Document Object Model, because that will help you to understand the topic better.
A brief note on DOM
Document Object Model is an interface that allows scripts and programs to dynamically access and update content(e.g. text, image etc.), structure and style of HTML, XHTML and XML documents. For this discussion, we will focus on HTML documents only. Document Object model is a W3C recommendation.
<!DOCTYPE html> <html lang="en"> <head> <meta charset=utf-8> <title>A simple HTML document</title> </head> <body> <h1>This is a simple HTML document</h1> <p>w3resource web development tutorial</p> </body> </html>
Now, DOM representation of the above code is following:
All those blue boxes are called as Nodes.
Write data to HTML document
Now, we will see how you may write some text in an HTML document. The following JavaScript code may be used to create a new paragraph in an HTML document and add some text within that.
var w3r_text = "This text will be added to HTML"; //creates a new paragraph element var newParagraph = document.createElement("p"); //creates text along with output to be displayed var newText = document.createTextNode(w3r_text); //created text is appended to the paragraph element created newParagraph.appendChild(newText); // created paragraph and text along with output is appended to the document body document.body.appendChild(newParagraph);
Read data from HTML document
Want to read data from HTML document? even easier. Let's see how you may do that. This is the JavaScript code we will use for this example.
var shdata = document.getElementById('shtxt').innerHTML; alert(shdata);
So, in the first line, we are collecting the text within the paragraph, whose id is - shtxt.
'document' refers to the document where the script is being run,
'getElementById' selects the element whose id is 'shtxt' and innerHTML selects the actual text.
We store that value in the variable 'shdata' and then, by using alert command, the text is displayed.
Here is the HTML code where the JavaScript above is added:
<!DOCTYPE html> <html lang="en"> <head> <meta charset=utf-8> <title>A simple HTML document</title> </head> <body> <h1>This is a simple HTML document</h1> <p id="shtxt">w3resource web development tutorial</p> <p><a href="#" onclick="Showdata();">Show text</a></p> <script src="fetch_text.js"></script> </body> </html>
Notice that, when you click on the link, code within the Showdata() is called.
This is the most simplest form of accessing data from HTML document.
There are many of a DOM commands which may be used to access data from HTML document.
Refer DHTML manual