< JavaScript

Runtime Document Manipulation

JavaScript can manipulate an HTML document that has been loaded into the browser using standard DOM (Document Object Model). Let's see an example:

<!DOCTYPE html>
<html>
<head>
<script type="text/JavaScript">
function displayMessage() {
  var divObj = document.getElementById("messageText");
  if (divObj) {
    divObj.innerHTML="<b>This is the new Message from Javascript</b>";
  }
}
</script>
</head>
  <body>
      <input type="button" value="Display Message" onclick="displayMessage();" />
      <div id="messageText" style="width:400px; height:200px; color:#00FF00"></div>
  </body>
</html>

When this html document is loaded into a browser, the browser displays a "Display Message" button. When we click this button, the text "This is the new Message from Javascript" appears within the messageText div container in bold text.

Note that the JavaScript function displayMessage() has altered the contents of the html document by adding the text and providing the bold styling.

  
var divObj = document.getElementById("messageText");

This document object is a representation of the loaded HTML. By using its getElementById() method, and by passing the id/name of the HTML element, we can tap to the element's DOM representation (in this case a div tag) and add a new HTML element to the current HTML document by using the innerHTML property.

This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.