ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Replacing HTML Content using JavaScript

Updated on October 30, 2011

Published: October 7, 2011

Updated: October 30, 2011

While viewing the source code from a number of sites one day, I noticed a large number of elements that contained no data. I started to wander why a web designer would place elements on a web page to display nothing. Then I realized that those empty elements were simple place-holders. Blank areas of the screen that the designer would later manipulate.

One very useful ability provided by JavaScript is the ability to replace the content of elements in an existing HTML document that was previously displayed, even empty elements. There are many reasons that a web designer may choose to take advantage of this ability but providing interactive pages is a likely goal.

JavaScript: The HTML stimulant
JavaScript: The HTML stimulant

The retrieve HTML form data hub displayed the retrieved data on a new page. Although that method in fact displayed the data, sometimes displaying the data on the same page from which it was retrieved enhances the appeal of the site.

Accomplishing this simple feat requires using another technique which employs the getElementByID() built-in JavaScript function. Did I mention that JavaScript is case sensitive? Well it is so when you use previously defined functions, make sure you get the upper-case and lower-case letters correct or you will receive syntax errors when the JavaScript interpreter fails to locate the function.

The getElementById Function

In JavaScript, the getElementById() function provides the capability to replace data in an element previously included in a document and identified by an id attribute. You include the idattribute within an HTML tag. For instance, to include the id attribute to identify a form as the contactForm, we would include the id attribute in the <form> tag as follows:

<form id="contactForm"> ... </form>

Now that we have identified the form in our HTML document, we can now refer to that form in a script.

The following line from a code snippet illustrates the general form or syntax for using the getElementById() included JavaScript function:


document.getElementById(elementId).innerHTML="new content";

In the code-line shown, document is the current or parent document that contains the getElementById() function. The elementId enclosed in parenthesis refers to the ID of the element to be modified. The innerHTML="new content" portion of the statement directs the browser to replace the inner HTML area or the space between the HTML element tags with the content represented by new contentbetween the quotation marks. Notice also, the periods located within the statement. These punctuation marks are necessary and separate the object from the method and action to be taken.

Using this function also illustrates the relationships between elements in the W3C HTML Document Object Model (DOM). Although the Internet is not under a particular organization's control, the W3C or World Wide Web Consortium develops standards for web development.

Under the DOM, a document is considered to be the parent or highest level object in the web page. Borrowing the concept of objects from Object Oriented Programming (OOP) led to the inclusion of attributes and methods within objects. Under this guide, the getElementById() method is included in the document class and may refer to any child element of the parent document as long as the element contains the id identifier, which the method uses to locate the target element.


So what can we do using the getElementById() function, Let's first prepare by creating another table after the first table in the <body> portion of the the HTML code. The following code snippet creates a table that does not display anything. Forgive me for not including a screen shot of the table display when the HTML code runs but the display would resemble a picture of the proverbial polar bear in a snow storm -- just a lot of white.

<table style="background-color:LightSkyBlue" border="1">
  <tr>
    <td id="ic1"></td><td id="ic2"></td>
  </tr>
  <tr>
    <td id="ic3"></td><td id="ic4"></td>
  </tr>  
  <tr>
    <td id="ic5"></td><td id="ic6"></td>
  </tr>
</table>
Click image to enlarge
Click image to enlarge

Looking at the screen shot to the right shows the input form with the empty form added. I gave the form a blue background so the position of the new form would show up in the screen shot. Notice the very small size of the table (small blue box).

So, with the second table added, we can now add the code using the getElementById() method to extract the data from the form and display that data in the second table. The code to perform these actions follows:

<script type="text/javascript">
function commitData() {			    document.getElementById("ic1").innerHTML="First Name";
document.getElementById("ic2").innerHTML=document.contactForm.fname.value;
document.getElementById("ic3").innerHTML="Last Name";
document.getElementById("ic4").innerHTML=document.contactForm.lname.value;
document.getElementById("ic5").innerHTML="E-mail Address";
document.getElementById("ic6").innerHTML=document.contactForm.emAddress.value;
}
</script>
Click image to enlarge
Click image to enlarge

What have you learned?

view quiz statistics

In the sample, you place the above code in the <head> section of the HTML document and call the function using the onclick event (more on the onclick event in a later hub). The onclick event fires when the user clicks a button you supply as an <input> element in the form used to supply the data. This is not the only way to use the getElementById() function but is the method used by the author for this example. Experiment with the function to really learn the versatility of the method.

One Quick Note:

You will notice that in most of my code examples the code is formatted with indentations. These indentations are called white space and simply improve the readability of the code for a human viewer.

Computers do not care about the white space and parse that part of the code out of the running version of the program.

However, the white space does make debugging the code easier and when working with HTML code the white space makes locating missing tags a breeze. This technique is also helpful when working with other languages.

Would you like to learn more?

Now that you have learned how to create a form, retrieve user input from the form, and replace the content of existing HTML elements, you may like to validate what the user enters in the form before you accept the input or learn more about the onclick event. Hubs dealing with the onclick event is coming soon.


Was this hub useful?

Your comments are always appreciated!

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)