Blog

Adding and Removing Page Elements with jQuery

Excerpt by Don Kiely

Not only can you change the appearance of the page with jQuery and update the content of elements on the page, you can even add and remove elements to and from the page dynamically! Now, we're talking real power: you can essentially rewrite the page on the fly using jQuery. Of course, you have long been able to do this using plain JavaScript, but it would take a lot more code and work, and you'd have to deal with nasty cross-browser issues.

The html method you learned about in the last section has rudimentary support for adding new elements to a page, embedded within a string. But that technique requires that you build a string containing the new elements. The difference between that technique and the ones you'll learn about in this section is that with these new techniques you can add a new element anywhere on the page, before or after existing elements, without building a string first. It's much more flexible and efficient this way.

jQuery has a few methods for adding elements, and one to remove elements. (There are a few others that can add and remove content, but this section focuses on the primary, most straightforward techniques.)

  • The insertBefore and insertAfter methods insert the new element you define immediately before or after all the elements in the wrapped set, as the sibling of each element. (A sibling is an element at the same level in the DOM hierarchy, with the same parent element, as another element.)
  • The prependTo and appendTo methods insert the new element you define as the child of each element in the wrapped set, either at the beginning or at the end of the child content.
  • The remove method removes all elements in the wrapped set from the page.

It is important to understand that adding and removing elements change only the in-memory DOM used to render the page, and leave the page source unchanged and unaffected.

One of the many ways you can make use of dynamically adding and removing elements is to handle the case where JavaScript is not available in the user's browser, whether because the browser doesn't support it or the user has it turned off. For example, you may build a page like the one shown in Figure 1 that has a highlighted notice at the top of the page along with a second paragraph that JavaScript code removes when the page loads. Therefore, if the browser doesn't have JavaScript available, the notice and second paragraph remains on the page.

the page when javascript is not available

Figure 1. The page when JavaScript is not available.

For users that have JavaScript available and enabled, there are several changes to the page, as you can see in Figure 2. The JavaScript notice and following paragraph are removed, a secret message appears, a button that can hide content appears, and NOTICE!/END NOTICE! is added to the beginning and end of every paragraph. The page is quite different from its non-JavaScript version!

the page when javascript is available

Figure 2. The page when JavaScript is available and enabled.

If the user clicks the button, code in the page removes both the button and the snarky paragraph about everyone being able to see the content, as shown in Figure 3, leaving behind only the Michael Pollan quote with good advice about eating habits. Non-JavaScript users don't have the capability of removing that content. As you can see the page demonstrates a number of different scenarios for controlling content through code using jQuery.

The following HTML code defines the starting content of the page in the body section (we've removed some of the text content to make it easier to focus on the structure of the page). Notice that one p element has a class associated with it, and the other two have an id value.

<h1>Add and Remove Elements</h1>
<p class="noJavaScript">
 We're sorry, but to use this page you must be using a
browser with JavaScript enabled. This may mean....</p>
<p id="noJS">
 It really is a shame that you don't have JavaScript
enabled. This page contains the ultimate secret....</p>
<p id="everyone">
 Everyone can see this content, whether you're hip and 
JavaScript enabled or not. Unless you press....</p>

The noJavaScript CSS class, defined in the page in a style element rather than in a separate stylesheet, adds the red border and yellow background to the first paragraph.

<style type="text/css">
 .noJavaScript
 {
 background-color: Yellow;
 border: 2px solid Red;
 padding: 5px 5px 5px 5px;
 }
</style>

The first block of JavaScript code in the page makes all of the initial changes to the page when it loads, and is enclosed in the jQuery ready function. Keep in mind that none of this code executes when JavaScript is not available.

The first part of this block of code uses the remove method to remove the highlighted notice and the following paragraph, using selectors appropriate to select those elements. That's how easy it is to remove elements from the page! And if the selectors selected multiple elements, all those elements would be history.

$(function () {
 $('p.noJavaScript').remove();
 $('p#noJS').remove();

The next statement dynamically adds the paragraph with the secret that only users with JavaScript enabled will be able to see. Notice that this statement uses a new form of the jQuery function, passing the HTML markup in a string as the sole argument to the function. This causes jQuery to parse and select the markup—as it does with a regular selector—but doesn't yet insert it into the DOM. The insertAfter method takes care of that task, inserting the new paragraph immediately after the h1 element as its sibling. The argument to the method is a selector that selects the elements on the page that you want to place the new paragraph after. On this page, it will insert a single instance of the paragraph after the sole h1 element on the page.

$('<p id="JavaScriptOn">Eat food. Not too much. Mostly
plants. -- Michael Pollan</p>').insertAfter('h1');

NOTE: If there were more than one h1 element on the page, the insertAfter method call would add the new paragraph immediately after each of the h1 elements. You can easily test this by adding more h1 elements on the page. If you really only want one instance of the paragraph on the page, you'd need to change the selector that you pass to the insertAfter method, such as by using the :first filter.

The next statement dynamically adds the button to the page. The string defining the button is again passed to the jQuery function, but this time the code uses the insertBefore method to insert it immediately before the p element with an id value of everyone.

$('<button type="button" id="buttonRemove">Remove Non-
Sensitive Content</button>').insertBefore('#everyone');
The final two statements in the first code block take care of adding the NOTICE!/END NOTICE! to the beginning and end of all p elements on the page. It is important to understand that at this point, there are only two p elements on the page; the others have been removed. That's why back in Figure 2 only two paragraphs are visible. This code uses the prependTo method to insert NOTICE! at the beginning of each paragraph, and the appendTo method to add END NOTICE! at the end of each paragraph, with spaces needed to keep the new text separate from the old.
$('<strong>NOTICE! </strong>').prependTo('p');
$('<strong> END NOTICE!</strong>').appendTo('p');
The second and final code block on the page wires up the click event function of the Remove Non-Sensitive Content button, buttonRemove, that the code added dynamically in the other code block. The event function does two things: removes the paragraph that contains “ hip ” (with leading and trailing spaces to avoid matching that string embedded in words) and removes the button.
$(function () {
 $('#buttonRemove').click(function () {
 $('p').remove(':contains(" hip ")');
 $('button').remove();
 });
});

The one big thing that is different in this code is that it passes a jQuery filter to the first remove method. Without that filter, the statement would remove all p elements on the page. But by filtering the wrapped set passed to the remove method by the jQuery function in that statement, it filters the p elements to be removed to only those that contain the hip string. In this statement you could easily have included the filter in the selector in the jQuery function, but in more complex, chained statements that might not have been possible. JQuery is a very flexible library indeed.

NOTE: The code that wires up the buttonRemove click event function didn't have to go into its own jQuery ready function. It could have gone into the other code block, immediately after inserting the button to the page. It's just personal style to keep event function definitions separate to make the code a bit cleaner and easier to maintain, but there really is no compelling reason to do so. Do it however works best for you.

One of the important lessons in this section, besides how to dynamically add and remove elements, is that the jQuery selector has uses far beyond the jQuery function. You'll definitely want to make sure you practice creating selectors in a wide variety of scenarios so that you are able to create selectors to get references to exactly the page elements you want.

WARNING! The elements you remove using the remove method still appear in the page source. So users with JavaScript can still see the message for people without JavaScript, and those without JavaScript could see the secret embedded in the code in the page. So this is not a technique for protecting content that you want only certain people to see.

ldn-expertdkielyThis post is an excerpt from the online courseware for our ASP.NET 4.0 AJAX and jQuery Using Visual C# 2010 course written by expert Don Kiely.



Don Kiely

Don Kiely is a featured instructor on many of our SQL Server and Visual Studio courses. He is a nationally recognized author, instructor, and consultant specializing in Microsoft technologies. Don has many years of teaching experience, is the author or co-author of several programming books, and has spoken at many industry conferences and user groups. In addition, Don is a consultant for a variety of companies that develop distributed applications for public and private organizations.


This course excerpt was originally posted October 09, 2012 from the online courseware ASP.NET 4 AJAX and jQuery Using Visual C# by Don Kiely

AJAXC#ASP.NET