The Most Popular Content Manipulation Methods in jQuery


As we move forward in learning bigger and better things about jQuery, we find the need to go beyond just using selectors to grab the content we want. The large number of selectors and filters available to us are a lot to learn, but once we are fluent with them, we can then start using other jQuery methods to manipulate the content in the DOM. We can create, remove, change, add, animate, or do pretty much whatever we want with that content. Let’s start testing this out now!

Creating HTML Content in jQuery

With jQuery, not only can we select elements from the page like a pro, we can easily create new HTML on the fly. To do this, all you have to do is pass a string literal containing valid HTML to the jQuery $() function. It would look something like this.

var rick = $("<h2>I’m Rick James B3@+ch!</h2>");

There you go, you now have a rick variable who oh so eloquently is able to tell you who he is inside of header 2 tags. There are a couple of ways to use the html() method, as well as the text() method. Here is a table with the summary of how to use these methods.

Method Name

Use Case

html() or length Returns the actual HTML of the first element matched
html(newhtml) Inserts the HTML provided into every matched element
text(index) Returns the text inside of the first element matched
text(newtext) Inserts the text provided into all matched elements

The general idea with these methods is that if you do not provide any arguments to them, whether HTML or text, they will go out and fetch what is in the matched elements. If you do provide HTML or text as an argument to these methods, then they will insert this content into whatever your selector matches. Quite intuitive!

Here is an example of using a few of these different methods using the following code.

jquery html text

The output above is simply loading up the example HTML and jQuery like we have been in a local browser, then running the code using firebug. You can also test this below, just click on ‘Run It’ to make it run!

In this example we made use of a few different jQuery methods. First, we grabbed the ul element on the page and then used the .html() method on that element without passing in any arguments. This returned all of the HTML that was inside of the ul we had selected. That snippet of HTML was then stored in a variable named rawhtml. On the next line, we selected the b element that is inside of the parent with id of #output. Once we had the element we wanted, the b tag, we ran the .text() method on it passing in the rawhtml. Now the cool thing about this is, when we pass in the raw html, the .text() method actually escapes the HTML for us for use in the page as actual text, not real HTML. The .html() method on the other hand, would create real HTML in the page. The program then uses the jQuery $() function to create a snippet of HTML and stores that in the variable named newhtml. Finally we use the .html() method and pass in our new HTML element, then run the .text() method and pass in some text. This gives us just some simple examples of using .text() and .html().

Attribute Manipulation with jQuery

Another way to work with the content on the page is by getting or setting the attributes of certain elements. jQuery provides the .attr() method for just this purpose and it can be used in a few different ways, depending on what you do or do not pass as arguments to the method. This table shows all of the different ways you can use the .attr() method.

Method Use Case
attr(name) Retrieve the value of the given attribute in name on the first matched element. If the element does not have the attribute given, undefined is returned.
attr(properties) By passing an object literal, you can set many attribute values in one swoop.
attr(key,value) Using this approach will set the attribute and value to all matched elements.
attr(key,fn) This approach uses a function to compute a value, then assigns it to the given attribute.
removeAttr(name) You can also remove the given attribute from all matched elements using this method.

Here, we’ll try out a couple of the different methods for using the .attr() method. First we’ll use the approach of passing in an object literal, and then we’ll use the method of simply passing in a key, value pair. These are probably the more common use cases of this method. The code looks like so:

jquery attr method

This is pretty cool. First, we create a new li element which has an anchor tag in it, but it has no attributes set. Then we append that li into the DOM after the li which has the class of framework. Now that it is in the document, we then fetch the anchor tag by it’s id of #goog. At this point we can use the .attr() method and pass in an object literal which has both an href property and a target property. This completes our anchor tag, and it is now a live link that goes to a webpage in a new browser window based on the attributes we set on it!

The second portion of this example is pretty easy. It’s simply a variation of one of the examples already covered earlier, but instead of using the .addClass() method, we use the .attr() method and pass in a key, value pair. What this does is assign the property with the given value to all matched elements.

Inserting Content With jQuery

jQuery provides many ways to insert new content into the document. Maybe you have created some new HTML on the fly, grabbed some elements with a selector, or have new content to insert as a result of a successful AJAX request, in all of these cases you’ll need some way to actually place this content into the page. You’re most likely familiar with the append method in jQuery, but there are several more ways to insert content as well. Here is a table of the most common methods to use for this process.


Use Case

append(content) Appends the provided content to the inside of all matched elements.
appendTo(selector) Appends the matched elements to a different set of matched elements based on the selector passed in. moves elements
prepend(content) Prepends the content given to the inside of all matched elements
prependTo(selector) Prepends the matched elements to a different set of matched elements based on the selector passed in. moves elements
after(content) Inserts content after, and outside of all the matched elements
before(content) Inserts content before and outside of all the matched elements
insertAfter(selector) Inserts all of the matched elements after a different set of elements based on the selector given
insertBefore(selector) Inserts all the matched elements before a different set of elements based on the selector passed in

We can take a bunch of these methods and apply them to a document to see how they work. Let’s check out the result!

jquery append prepend after before

Note: Click ‘Run It’ below to watch this in action. If you want to try it multiple times, just refresh this web page after it runs to reset the application and then run again.

As you can see, you can combine all of these different methods to manipulate the page in any way you like. Just use your imagination and try all kinds of combinations to see what kinds of effects you come up with.

Using jQuery to Wrap, Replace, or Remove Content

In addition to appending and prepending elements, as well as moving them around using appendTo and prependTo, jQuery also provides even more methods for doing things like wrapping existing HTML inside new HTML. You can also simply replace content in the page with new content, or remove it altogether from the document. As always, jQuery provides many many ways to accomplish whatever you are trying to do with your application. Listed here are all of the methods to complete these types of tasks.


Use Case

wrap(html) Wraps each matched element with the specified HTML content
wrap(element) Wraps each matched element with the specified element
wrapAll(html) Wraps all the elements in the matched set with the specified HTML content
wrapAll(element) Wraps all the elements in the matched set into a single wrapper element
wrapInner(element) Wraps the inner child contents of each matched element with a DOM structure
replaceWith(content) Replaces all matched elements with the specified HTML or DOM elements
replaceAll(selector) Replaces the elements matched by the specified selector with the matched elements
empty() Removes all child nodes from the set of matched elements
remove() Removes all matched elements from the DOM
clone() Clone matched DOM elements and selects the clones
clone(bool) Clone matched Dom elements, and all their event handlers, and select the clones

You’ll notice there are two way to implement the .clone() method. This is because by default when you use this method, it copies the elements, but not any events that may be bound to those elements. There may be instances when you do want to include those bindings, since why would you want to go and recreate those bindings if you don’t need to? In this case, simply pass the true value as the second argument and you’ll have a copy of the element and any bindings already associated to it.

Like the other groups of methods, we can string a few of these together and create a little example that shows them in action. If you have your own sandbox development environment setup, go ahead and test these out as well. Again, repetition and practice will drive the concepts home! Here is the snippet of jQuery we’ll run in firebug on our example HTML.

Working With CSS Using jQuery

You will often see developers use jQuery to retrieve and update CSS styles on the fly. There are just a handful of ways to use the .css() method and it is pretty straightforward. Here they are.


Use Case

css(name) Returns the value for the named CSS property for the first matched element
css(properties) This option is really convenient. Pass an object literal to the method and set multiple CSS values at once
css(property, value) Sets a single style property to a value on all matched elements. If a number is given, it will be auto converted to a pixel value, except for z:index, font-weight, opacity, zoom, and line-height.

In addition to directly manipulating the CSS itself, you can do things like simply add a predefined class. You can also remove and toggle a class with jQuery methods. This approach is a little easier in my opinion, and it is the approach we have been using so far to show the effect of jQuery methods on our documents. We happened to take a different approach for these example. In many tutorials, developers will wrap an element with a border using the .css() method. In these examples we have been using the .addClass() and .removeClass() methods to add and remove various predefined classes from the Twitter Bootstrap framework. It’s pretty cool!

Here are some of those additional CSS methods.


Use Case

addClass(class) Adds the provided class or classes to each of the matched elements
hasClass(class) Returns true if the given class is present on at least one of the set of matched elements
removeClass(class) Removes all of the given classes from the set of matched elements
toggleClass(class) Adds the given class if it is not present, and removes it if it is
toggleClass(class, switch) Adds the class if the switch is true and removes the class if the switch is false

Thanks to the simplicity of this approach, we have been using the .addClass() and .removeClass() methods to show how we can update the look of elements on the page in real time. It appears as though these methods are changing the class attribute but the way they actually work is that jQuery modifies a DOM property called className. The .addClass() method creates or adds to the property and the .removeClass() deletes or shortens it. The .toggleClass() method works a little differently and it is really cool. It alternates between adding and removing class names creating a toggle effect. You can assign this behavior to an event handler like a click event and then create a slick on and off feature by clicking an element. The great thing about these methods are that they avoid adding a class if it already exists on an element while also correctly handling instances where several classes are applied to just one element.

This episode was a great overview for any content manipulation tasks you may have. jQuery makes quick work of this instead of having to rely on the native DOM and native JavaScript. This way our scripts are easier to read and more concise.