How to Add HTML to a Page with jQuery

jQuery can be used to add HTML to a page. You can add all sorts of HTML, images, just about anything, and completely change the layout of the page using jQuery. Doing so isn't really a good idea, because it can get really, really confusing to figure out what's coming from where and also can be more difficult to maintain in the future when you need to change the page.

In any event, adding HTML for things like error messages or in order to add data to a page is quite common. Think about a travel site that looks up flight information. You click a button, and it builds the results dynamically, right on the same page. Those sites use JavaScript, many times jQuery, to accomplish this feat.

But before you go changing HTML you should learn how to add HTML to a page.

This listing shows a simple HTML page that creates a list of items.

<!doctype html>
<html>
<head>
<title>jQuery</title>
</head>
<body>
<h1>Adding HTML</h1>
<ul id="theList">
    <li>Here's 1</li>
    <li>Here's 2</li>
</ul>
</body>
</html>

A page viewed in a web browser looks like this one:

image0.jpg

The page uses an unordered list with two items. You can add another item to that list with the jQuery append() function. Doing so means selecting the <ul> element, which you already know how to do, and then calling the append() function. Here's an example to add a third item to the list:

$("#theList").append("<li>Here's 3</li>");

As you can see, you select the <ul> element using an ID selector and then call the append() function with the HTML to add. Doesn't get much simpler than that.

This listing shows the final code. Note that jQuery has been added to it in the <head> section and the append() function is within the ready() function.

<!doctype html>
<html>
<head>
<title>jQuery</title>
<script type="text/javascript"
   src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.1.min.js">
</script>
</head>
<body>
<h1>Adding HTML</h1>
<ul id="theList">
    <li>Here's 1</li>
    <li>Here's 2</li>
</ul>
<script type="text/javascript">
$(document).ready(function() {
    $("#theList").append("<li>Here's 3</li>");
});
</script>
</body>
</html>

When viewed in a browser, the result looks like this:

image1.jpg
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com