Quick tip: XMLHttpRequest and innerHTML

Share this article

XMLHttpRequest is one of modern DHTML’s best kept secrets. If you haven’t encountered it before, it’s a method of making an HTTP call back to the hosting web server without refreshing the whole page – a kind of remote scripting on steroids. Originally a Microsoft extension, it’s been adapted by both the Mozilla browser family and (as of version 1.2) Safari. The Sarissa library discussed previously offers an abstraction layer for the different browsers, or for a more lightweight approach this code from jibbering.com (which makes use of IE’s JScript conditional compilation) works perfectly.

Getting the most out of XMLHttpRequest generally involves using server-side generated XML, which can be retrieved by your JavaScript application, parsed and used in more complex logic. However, for a quick fix the following code will load an HTML fragment from a URL and insert it directly in to a page:


function loadFragmentInToElement(fragment_url, element_id) {
    var element = document.getElementById(element_id);
    element.innerHTML = '<p><em>Loading ...</em></p>';
    xmlhttp.open("GET", fragment_url);
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            element.innerHTML = xmlhttp.responseText;
        }
    }
    xmlhttp.send(null);
}

Call the above function with the URL of the HTML fragment to be inserted and the ID of the element in which it should appear. It relies on the jibbering.com code to set up the xmlhttp variable.

It’s definitely quick and dirty, but it’s also a great quick demonstration of the power of the XMLHttpRequest extension.

Frequently Asked Questions (FAQs) about XMLHttpRequest and innerHTML

What is the difference between innerHTML and outerHTML?

innerHTML and outerHTML are both properties of an element in the Document Object Model (DOM). The main difference between them lies in what they return and modify. innerHTML gets or sets the HTML content (inner HTML) of an element, while outerHTML gets or sets the HTML content, including the outer wrapper of the element. In other words, innerHTML deals with the content within the element, and outerHTML deals with the entire element, including the tags.

Is it safe to use innerHTML?

While innerHTML is a convenient way to inject HTML into a web page, it can pose a security risk if misused. If you’re inserting user-generated content into a page, and you use innerHTML, you could be opening yourself up to a Cross-Site Scripting (XSS) attack, where malicious scripts are injected into your web page. To avoid this, always sanitize user-generated content or use safer methods like textContent or createElement.

How can I use innerHTML to add multiple elements?

You can use innerHTML to add multiple elements by concatenating the HTML strings for each element. For example, if you want to add two paragraphs, you could do something like this:
element.innerHTML = '<p>First paragraph.</p>' + '<p>Second paragraph.</p>';
This will add two paragraphs to the element.

Can I use innerHTML to insert SVG elements?

Yes, you can use innerHTML to insert SVG elements. However, there are some caveats. The SVG namespace is not preserved when using innerHTML, which can cause issues in some browsers. If you’re having trouble, consider using the createElementNS and appendChild methods instead.

Why is my innerHTML not working?

There could be several reasons why your innerHTML is not working. One common reason is that the element you’re trying to modify does not exist at the time your script runs. This can happen if your script is loaded before the body of your page. To fix this, you can either move your script to the bottom of your body tag, or wrap your code in a window.onload function.

Can I use innerHTML with XML documents?

No, innerHTML is not supported with XML documents. It is a property of the HTMLElement interface in the HTML DOM, and is not available in the XML DOM. If you’re working with XML, you’ll need to use methods like createElement and appendChild instead.

How can I remove all child elements of a node?

You can remove all child elements of a node by setting the innerHTML property to an empty string. For example:
element.innerHTML = '';
This will remove all child elements of the element.

Can I use innerHTML to insert text into a text node?

No, innerHTML can only be used with element nodes. If you want to insert text into a text node, you should use the nodeValue or textContent property instead.

How can I use innerHTML to replace an element?

You can use innerHTML to replace an element by setting the innerHTML property of the parent element. This will replace all child elements of the parent, including the one you’re targeting. For example:
parentElement.innerHTML = '<p>New paragraph.</p>';
This will replace all child elements of parentElement with a new paragraph.

Can I use innerHTML in Internet Explorer?

Yes, innerHTML is supported in all major browsers, including Internet Explorer. However, there are some differences in how browsers handle certain aspects of innerHTML, so it’s always a good idea to test your code in multiple browsers.

Simon WillisonSimon Willison
View Author
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form