AJAX programming: client-side web page manipulation

On the client, a key component of an AJAX application is the ability to modify elements of the currently-loading web page from the client. There are usually two common steps:

Defining element IDs

Within the actual HTML of our page (not the JavaScript sections), we assign an ID to those components of the page that will potentially change. Typical candidates will be elements such as <div>, <p> or <span>. We add an id attribute, and assign it some string of our choosing:

<p id="paratochange">This paragrah may change later!</p>

Changing the HTML of an element from JavaScript

At some point within our AJAX application, we'll want to update part of the page in response to a user action.

So within the JavaScript section(s) of our page, we use the previously1 assigned id to refer to one of the HTML elements on our page. To do so, we use the JavaScript document.getElementById() call to find the given element by its ID. Provided that such an element exists, this call returns us an HTMLElement object. We can then set the object's innerHTML property to change the contents of the corresponding div, paragraph etc. For example:

var element = document.getElementById("paratochange");
element.innerHTML = "See, told you it could change!";

Occasionally, it's more convenient to change some other property of the element. For example, if we were changing the text of a button in an HTML form, we'd change the button's value property:

function setFormLanguage(lang) {
  var captionStr = 'Search';
  if (lang == 'ES') {
    captionStr = 'Buscar';
  } else if (lang == 'FR') {
    captionStr = 'Recherche';
  }
  var butt = document.getElementById("searchButtonId");
  butt.value = captionStr;
}

When to insert HTML manipulation code

As well as knowing how to manipulate the contents of our web page, we need to insert the corresponding JavaScript code at an appropriate point within the page's "life cycle": when the user clicks on some button or "active" element, when data is received from the server etc. For this, use JavaScript event handler functions.


1. By previously, we mean in terms of the order in which things exeute on the browser, not necessarily the order in which things are physically defined in the HTML file!


If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.