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.
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:
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:
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.
When viewed in a browser, the result looks like this: