Read from and write to 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.
Let's take a simple HTML page like following:
<!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
var w3r_text = "This text will be added to HTML"; var newParagraph = document.createElement("p"); //creates a new paragraph element var newText = document.createTextNode(w3r_text); //creates text along with output to be displayed newParagraph.appendChild(newText); //created text is appended to the paragraph element created document.body.appendChild(newParagraph); // created paragraph and text along with output is appended to the document body
We have added comments next to each line of code, so that you can understand it. You may use our comments section to let us know if you have questions. If the code above is added to the HTML code we have begin with, it bo comes:
<!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> <script src="add_text.js"></script> </body> </html>
Did you see the new text in the HTML output now? So, that is how you may write to an HTML document.
Read data from HTML document
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.
<!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 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.
New Exercises:R Programming