Selecting HTML element contents with innerHTML and jQuery method

In this tutorial:

  • innerHTML
  • html()

It’s possible to change the content of an HTML element dynamically using JavaScript’s innerHTML method or $() in jQuery.

Using innerHTML

When writing JavaScript code, I always have most fun with innerHTML. It’s one of my favorite things to use in my apps. This JavaScript property gives us the ability to dynamically change the inner contents of an HTML element.

It can be pretty much any element. DIV, P, SPAN, TABLE, and even BODY.

innerHTML is used on websites like Twitter and Facebook, where the dynamic feed needs to be updated without having to refresh the page in your browser. But that’s only one example. How you choose to use it is only limited by your imagination.

Whenever the innerHTML property of an element is set to a value, such as plain text or HTML code, the element is refreshed dynamically with that value. This happens at the execution level of your program. In the same way you create an alert by calling the alert(); function, innerHTML will instantly change the contents of a given element on the line of code when it is called. As one would imagine.

But how do we select an element whose contents we want to change? In JavaScript, this can be done by writing following code:

var target = document.getElementById("an_element_id");
target.innerHTML = "new content";

From this moment, the element you have selected will now contain the value set to innerHTML, which is just the string: “new content.”

But you can also change the content of an element to actual HTML code. Displayed as HTML, not as plain text. If you do this, not only the content will be integrated into the element’s content, but the HTML will actually execute and render the HTML elements inside the target element:

target.innerHTML = "
<div>HTML content</div>

In this case, an actual DIV block with text “HTML content” will be embedded into the target element. So, the point is that you can either add plain text or HTML code inside other elements.

innerHTML is the original JavaScript function. In jQuery it has an equivalent, it’s just called html(“text”), where “text” is the string you want the entire contents of the element to be replaced. jQuery’s html() function actually uses JavaScript’s innerHTML behind the scenes. It just gives us an easier way of writing the code to select the target HTML element, using its minimalist syntax:

<div>New HTML code.</div>

Notice how, jQuery selector requires the # symbol before the element ID name. Doing it the “JavaScript way,” would imply creating the target variable, and messing with


…which is much more aesthetic clutter (but not performance-wise) than we probably need. jQuery’s html() method will work in all browsers that support it. Without jQuery you are left with writing code compatible with all browsers yourself.

jQuery Tutorials