Advanced Functionality in Manipulating the Page Using jQuery
 
 

One of the main advantages of jQuery is the HTML manipulation you can do with client-side scripting. Instead of sending the page back to the server to process, you can use jQuery to change the way HTML lays out on the page. This essentially changes the layout or structure on your page, and it can change the text that's shown to the user. In this article, we'll discuss the different page manipulation techniques you can use with jQuery.

Insert and Replace HTML

The jQuery framework lets you change any of the HTML code in your pages. The most common reason is to change HTML based on user input. You should note that HTML and text are different when working with jQuery functions. If you output to HTML, your browser assumes that the output is HTML and that you want to render it on the page. If you output text, the browser assumes that you want the literal text. You can see the difference by using the HTML and text functions.

Let's first create a div container that displays text and an HTML button. When the button is clicked, jQuery outputs the actual HTML for the text and the button.

The following HTML code is what we'll use to illustrate the way these two functions work.

<div>

 This <button id="button1">button</button> turns HTML to text.

</div>

As you know, this HTML code will show a div container with text and a button. When we click the button, we want to turn this HTML into plain text. The following jQuery code takes the HTML code and uses the text method to display it.

<script>

$( "div" ).click(function() {

 var html = $( this ).html();

 $( this ).text( html );

});

</script>

Notice that the above code captures the div container's click event and not the button. Even though we click the button, the button is contained within the div so that the div's click event can be captured. This is an important part of the code because within the function we use the "this" statement. The "this" statement points to the currently referenced object, which in this case is the div.

The variable declaration is assigned to "this" HTML. Since we've pointed to the div container, the html method gets the HTML contained within the container. Next, the "text" method is used to print the HTML string.

When you use the html method, HTML is printed to the screen and it's parsed by your browser. When you use the text method, any content including HTML code is shown as literal text. This distinguishable difference is important when you customize and output HTML and text in client-side scripting.

Wrapping HTML

In some cases, you might want to wrap current HTML within what is called a wrapper. A wrapper is placed outside of the HTML and becomes its parent container. This is often done using div containers.

If you recall, we discussed parent and child containers. Take a look at the following HTML code.

<div>

 <div id="child"> Child </div>

</div>

In the above code, the child div is contained within the main outer parent div container. The main outer div container is considered the parent. Any elements within the parent container take the parent container styles as their own unless you override them with child container classes. This is an important concept with you use the wrap and wrapInner methods in jQuery.

Let's first take a look at the wrap method. We'll use the following HTML code to illustrate.

<div> Container 1 </div>

<div> Container 2 </div>

<button>Wrap these containers</button>

We'll use the wrap method to contain these two elements within a wrapper that has its own background color set.

<script>

$(document).ready(function(){

    $("button").click(function(){

        $("div").wrap("<div style='background-color: blue;'></div>");

    });

});

</script>

In the above code, the button's click event is captured and a function that wraps the containers in a parent with a blue background is defined. This function wraps the child containers with a parent. The child containers have no style defined, so they take the parent's style. Since the style sets a blue background, these containers show a blue background when the button is pressed.

The wrapInner function works a little differently. Instead of wrapping HTML with a parent container, you wrap the inner content of the container. We can use the same HTML content that we used previously. Here is the HTML code again.

<div> Container 1 </div>

<div> Container 2 </div>

<button>Use the wrapInner method.</button>

The following jQuery code wraps only the text within the div containers.

<script>

$(document).ready(function(){

    $("button").click(function(){

        $("div").wrapInner("<b></b>");

    });

});

</script>

In the above code, we wrap the inner text with the HTML "bold" tags. This will set the content within the containers to bold format. This is much different than wrapping the div containers in a parent and has different effects depending on the wrappers that you use.

Copying HTML

JQuery gives you two main copying methods. The first one is the appendTo method. The second is the clone method. Both of these copy text from one location to another, but only the clone method leaves the original element intact. The appendTo method cuts the original code and places it after another element. This difference is important when determining which method you want to do and what you need to accomplish.

Let's first write the HTML code needed to illustrate these two methods. The following HTML has a parent div container with two child containers.

<div class="main">

 <div class="first">First</div>

 <div class="second">Second</div>

</div>

With this code, we can now use jQuery to append and clone these elements. First, let's use the appendTo method. The following jQuery code shows you how to use the appendTo method.

<script>

$( ".first" ).appendTo( ". second" );

</script>

In the above code, the div container with the class name "first" is appended to the element with the class name "second." It's important to understand the HTML layout after this code is executed. The HTML now looks like the following.

<div class="main">

 <div class="second">

    Second

    <div class="first">First</div>

 </div>

</div>

Notice that the "first" container has been cut from its original position and moved to the end of the "second" container.

Now let's take a look at the same code, but using the "clone" method. First, set up the HTML again.

<div class="main">

 <div class="first">First</div>

 <div class="second">Second</div>

</div>

Then, write the jQuery code adding the clone method to the command.

<script>

$( ".first" ).clone().appendTo( ". second" );

</script>

With the clone method, jQuery takes a copy of the original code and leaves it intact. Take a look at the results of the clone method.

<div class="main">

 <div class="first">First</div>

 <div class="second">

    Second

    <div class="first">First</div>

 </div>

</div>

Notice the major difference in the way the page's HTML is laid out. This is an important difference when you work with jQuery copy statements.

Deleting HTML

Part of manipulating page HTML is removing text. Just like the copy functions, you have two delete functions that you can use in jQuery. However, each one has different functionality when used. The different functionality is what you'll use to determine which one is right for your code manipulation.

We can use the same HTML code from the previous section to look at the way these jQuery methods work. The following HTML is a copy of the previous section's div containers.

<div class="main">

 <div class="first">First</div>

 <div class="second">Second</div>

</div>

With the HTML in place, now you can write your jQuery code. The following jQuery code uses the empty method.

<script>

$( ".first" ).empty();

</script>

With the empty method, we delete any text contained within the specified element. We specified an element with the class name of "first." Any text within this element will be cleared, but the HTML remains. The following HTML is the result of calling the empty method on the element.

<div class="main">

 <div class="first"> </div>

 <div class="second">Second</div>

</div>

Notice that the first div container HTML is still rendered but the text is gone.

Now, let's take a look at the remove method. The remove method not only deletes the text within a container but it also deletes the HTML. We can use the same HTML code snippet to illustrate the way the remove method works. Let's copy the HTML code again.

<div class="main">

 <div class="first">First</div>

 <div class="second">Second</div>

</div>

Now let's write the jQuery code similar to the previous example but with the "remove" method instead.

<script>

$( ".first" ).remove();

</script>

The remove method completely deletes the container. Take a look at what the HTML snippet looks like after the remove method is executed.

<div class="main">

 <div class="second">Second</div>

</div>

Notice that not only is the text gone but the entire element with the class name "first." That's the major difference between the remove and empty methods. You can use the empty method if you want to delete text only to insert text later. Use the remove method if you want to delete an element and no longer need it in future client-side code.

Other Ways You Can Modify Your Page

We covered some basic ways that you can modify your page contents using jQuery. JQuery has several other functions that you can use. Some of them incorporate the previous sections' methods as well. Let's take a look at some other ways you can manipulate HTML and text on the page.

We showed you how to use the html and text functions, but we didn't show you how to use them in a simpler way just to add content to your pages. We can again use the same div containers used in the previous section.

We've copied the HTML below.

<div class="main">

 <div class="first">First</div>

 <div class="second">Second</div>

</div>

Suppose we want to add another HTML element to the main container. We can do this using the html method. Remember that the html method adds code and renders it as HTML and not literal text. The following jQuery code shows you how to add HTML to your page.

<script>

$('.main').html('<b>Test</b>');

</script>

The result of this code is that both the first and second div containers are overwritten with the new HTML content. The result is the following HTML code.

<div class="main">

 <b>Test</b>

</div>

You probably don't want to overwrite your current HTML. It's more likely that you want to add the bold content to the main container without deleting the current content. You can do this by using the following code.

<script>

var html = $('.main').html();

$('.main').html(html + '<b>Test</b>');

</script>

Now your HTML looks like the following. The html method ultimately changes the "innerHTML" property for a specific element. The innerHTML element is

<div class="main">

 <div class="first">First</div>

 <div class="second">Second</div>

 <b>Test</b>

</div>

Suppose you want to only add some text to the element with no HTML formatting. The text method only adds text without deleting any HTML elements. Let's again look at the original HTML sample.

<div class="main">

 <div class="first">First</div>

 <div class="second">Second</div>

</div>

Suppose we just want to add "Test" to the main div container but don't want to add any formatting. The following jQuery code adds text to the container.

<script>

$('.main').text('Test');

</script>

Now, we have an HTML div container with the following text.

<div class="main">

 <div class="first">First</div>

 <div class="second">Second</div>

 Test

</div>

You can also modify page links using jQuery. The "attr" method changes the link and other attributes for a link. Take the following HTML code that contains a link element.

<a href="mysite.com" id="mysitelink">Mysite Link</a>

<button>Change the link and title.</button>

With the link and button defined, you can now use jQuery to dynamically set the link target. Right now, the link points to mysite.com. However, you might want to set a link element to a different location based on user feedback. In this example, the user feedback is when the button is clicked.

Take a look at the sample jQuery code.

<script>

$(document).ready(function(){

    $("button").click(function(){

        $("#mysitelink").attr({

            "href" : "http://mynewsite.com",

            "title" : "New Site Link"

        });

    });

});

</script>

In this jQuery code, the button click event is captured and the function uses the attr method to set the "mysitelink" element with a different href and title properties. When the user clicks the button, the link is changed to point to "mynewsite.com" and the title that shows when you hover over it displays "New Site Link."

This is another example of the completely dynamic way jQuery handles HTML elements on your page. You can dynamically respond to your users with any element after any input whether it's a button click, a mouse hover, a click of a link, or from input in a form. The speed at which jQuery responds to your users is much faster than the time it takes to process your pages on the server.