appendTo offers JavaScript Training Courses for Software Teams. In addition to this, we also offer free jQuery/JavaScript training videos for individuals on our YouTube channel. Below is a free video with an introduction to manipulating the DOM in jQuery:

Full Video Transcript

In this lesson we’re going to talk about jQuery’s DOM manipulation capabilities. First, a few terms we’ve been using so far just wanted to review with you. The first is the jQuery function which refers to the function used to create jQuery objects. It’s usually denoted by the dollar sign and then the opening closing parenthesis or the invocation operator. The jQuery objects, what returns from that jQuery function, it’s what we use to apply methods. We can also have chain-able methods, so we can sometimes use multiple jQuery methods on that jQuery object. Also, when we talk about the jQuery collection, that typically means the collection of matched elements held inside the jQuery object.

Taking a look at our first pieces of manipulation let’s talk about getting and setting with jQuery. There’s a few different jQuery methods we have that have this getter setter functionality. Let’s take a look at one here. With text we have a getter ability and a setter ability. Looking at our first line here we’re actually using text, but notice here we don’t actually … We’re not displaying any parameters to text. When that’s the case, actually let’s take a look at the jQuery API documentation. Note what we’re getting here. We return a string in that case. In our example here we’re saving that string to a variable and then we’re just going to alert and show that string.

Compare that with the setter functionality which we’re showing here next. We’re actually going to use a selector to grab the same div here, and then we’re supplying text a single parameter. Although this is the same method if we go ahead and back here to the documentation and take a look at text with one parameter is used as a setter. Note also that it returns jQuery here which indicates that when we use text as a setter it’s actually a chain-able method. Back here note that after text we’re able to chain another jQuery method on here on this final line.

Let’s go ahead and toggle and run the example here. There’s the alert that pulled the information. Note we got the text from both the first and second div, and it’s combined. Taking a look at the documentation here. I’m going to scroll back up to the top to show the getter functionality. Notice the result of the text method here they explain on this line. It’s a string containing the combined text of all matched elements. It’s important to note because other getters don’t function quite that way as we’ll see. Some new text was applied. You might have seen it there, as we were hiding it over 3 seconds.

One other thing that we can use in jQuery 1.4 and later it’s we can actually supply a function to be called by jQuery. We can supply a callback function and if we take, go ahead back here to the API documentation one more time, click down and look at the setter functionality, notice the parameters we get. We get an index. Since we might have a jQuery collection, that index will give us the current loop iteration and that will give us the text of the element that’s being currently looped over. This is a really, really easy way to append text to elements using the jQuery text method.

Here note that we are going to take text right here. That’s our parameter we’re specifying as the current text of this div that we got through our selector. Then we are pending more text to it here. Notice we’re returning that text. That’s the return value of our function. Whatever we return from this method is what jQuery is going to use to set the text inside of this div here. Let me go ahead and toggle and run this. Notice it was appended. If I run it again we get more text appended. Pretty cool stuff. Something to keep in your bag of tricks.

Taking a look at val, we have getter and setter functionality here as well and it looks quite similar. Val with zero parameters we’re going to get the value. It’s important to note though with val it’s not going to actually combine all of the different values from everything selected. In our example here we’re selecting one thing by ID. But let’s say we selected all the inputs on the page and we had 10 inputs. .val with no parameters would simply give us back the first matched elements value when append them all together, so we only get a single value back instead of 10 combined values.

That’s important to note and we’ll see that with some of our other getters, similar behavior that is. We’re going to alert that val so we’ve set it to a variable and we’re going to alert it here, just to show we’re able to get the value out. Then we’re going to set the val using the val method and a single parameter, which is the string we want to set the value to. Go ahead and go running this. Our alert and notes here that we were able to change the value.

We can actually get and set any attribute within an element. Taking a look at this. It’s a little different in that for the getter functionality for an attribute in, our case we’re just going to select this image with class cute that’s right here. Then we’re going to supply a single parameter attribute, this title parameter. Attribute with one parameter is a getter. It tells the attribute method what attribute we like to get. We’re going to get that attribute and we’re going to alert it here.

We also have setter functionality for an attribute. Here we’re actually going to once again use our selector engine to select this image with a class of cute. Then we’re going to supply 2 parameters, once again the attribute that we want to set. Now the second parameter will inform the attribute method that we’d like to use it as a setter. We would expect the title to now be what we’ve supplied here. Note once again that the setter methods are chain-able so we’ll chain a couple of extra methods on there.

Let’s take a look. I know how cute that leopard is there. He already looks like he’s about ready to eat somebody. But we’ll go with it. Note the title right now. It’s a cute baby leopard. We click run. There’s our titles. We’re able to get it. Once it comes back let’s go ahead and hover again to see what the title is. Indeed, we’re able to change the title. Any attribute can be changed here.

There’s even an HTML method that we can use to get and set HTML. Let’s take a look at that. Here we’re actually going to use HTML as a getter. Notice we’re going to select both of the paragraphs here and then use the .HTML method. HTML is different from text in that HTML will only return the first match selectors HTML. Instead of getting foo and bar smashed together, we only really should expect to get foo back from this HTML getter here. I’ve just thrown that right in line here into an alert as the first parameter for that alert. That alert should show foo.

Setter functionality take a look here and here. We’re actually specifying markup elements. jQuery is smart enough to recognize that. It’s going to create those elements using the Dom API for us and so we should actually have an em element inside of our paragraphs once the setter behavior occurs. Other important thing to note with the setter behavior is that it will actually set everything that was selected. It will use implicit iteration, going over both of these paragraphs here and here and set both of them to our new markup.

Let’s go ahead run and take a look. Indeed, we get foo and no implicit iteration occurred. Both of those paragraphs were changed, and you can tell here and we’ll just toggle to look at the source. There it is, the em element is there. Really cool stuff. That indicates that jQuery has very interesting capabilities for creating elements.

Let’s dig a little bit more into creating elements. There’s a couple of different ways we can create elements. Let’s start with one. One is to actually not do a find something do something type of behavior. We’re actually going to create something and then do something with it using jQuery methods. Note here that instead of using a selector I actually have inline HTML as a string with the starting and ending tags for a div. We’d expect a dev element actually to be in our jQuery object at that point, and then we can use jQuery methods on it.

There’s a whole series of jQuery methods that are specifically catered to adding elements to our webpage through the DOM. One of those for example is append to. Take a quick look at the page here. I want to note something specific here on api.jquery.com. Note this specific word, target. Every time you see a method that says target, the target can be a bunch of different things. Looking here note the first thing the target could be is a selector itself.

Going back to our slides note that we’ve supplied a selector as our target. What we’re doing is we’re creating a div and then we’re going to append it to any matches for this append container class. Now we only have one, but if we had multiple matches this div would actually be cloned and added to each one of those matches. Just go ahead and running this. Note that we now have our brand new div actually in our HTML now. Really cool.

Another thing we can actually do is we can have in place attributes within our div as we’re creating it. This is similar example to the last slide. The difference here to note is here we’re actually declaring an attribute in line. Note that I’m escaping here and here so I can still use double quotes. I could’ve simply used single quotes in these 2 positions and not used escaping, but I can be a little specific sometimes and I really like double quotes in my attributes. It’s a little neurotic, I know.

Again, I’m going to use the append to jQuery method. Note once again I’m going to use a selector to tell jQuery where to append our newly created div element. Let me go ahead and run this, and once again, note we are able to append that element and that the class here is actually applied for us. We can even nest elements when we’re creating them. A quick example of that note here that we’re actually adding in this inner em element within this div element. jQuery will be smart enough to recognize that and will produce this em element as well as the div element.

It’s important to note though that the jQuery objects collection after something like this, what we’re referencing and taking direct action on, will only be this div. Now the div inside does contain the em element, so if we do things like append that div to the page using a selector like we’re doing here, the div and the em will be appended. It’s just important to keep in mind that what’s actually in the jQuery object and what we’re operating against is this outer most div here that we’ve declared. Let’s go ahead and run this. Here we go, em elements within div. Beautiful.

Another general approach is available. It’s kind of taking an opposite field of things, and that’s, we’re going to use our find something and then do something with it mentality, but our do something is going to be creating elements. Taking a look here we’re going to grab all the paragraphs on the page with a class of image-ex, and then we have specific jQuery methods catered to adding DOM elements based upon what method we’re using. Let’s take a look at the example of that after.

After specifies content. Notice so after we’ll insert that content after each element in the set of matched elements. We can specify content. Note right here, it’s an HTML string. Going back here, note that’s what we have here. We have an HTML element, an image that we’re going to insert. Let’s go ahead and toggle and run this. There we go. Very cool. Note the image was inserted after the paragraphs. I know, that’s shocking.

The decision for whether to use the selector first approach which is what we just saw versus the create element approach which was on the previous slides, really comes down to what sort of other functionality you want to have as part of your jQuery statements that you’re writing. For example, if I’m going to create an image and then I want to do a bunch of things after that, let’s say add an extra attribute here like we see with this attribute method. Or we haven’t talked about events in great detail, but I might want to add a click event for that image let’s say for example. There’s a click method available for that we’ll see in the next lesson.

You might want to create the image, chain on a bunch of jQuery methods related to that image, like adding event behaviors or the attribute that we see here, and then once you’re done adding all of that stuff the last thing you can do is use one of the DOM manipulation methods available to us to append the image to the page.

Take a look at that. Let’s go ahead and toggle this and run it. Here we go. You might’ve even seen there for a split second the alt logo was shown before the image loaded. Very cool. Something else to note here. This image was actually cloned for us. We’ve got 2 of them. Was in the last slide as well. That’s because we once again have implicit iteration happening for us.

Here’s the opposite approach. Let’s say we wanted to select some paragraphs from the page, and we had some specific things we wanted to do to those paragraphs, maybe adding event behaviors, maybe doing something like we have here, adding this specific class special.

Then after doing all of those things or along with doing all those things we might at some point just want to add an image after each of those paragraphs. This will be probably a better way to do that. Then if we had just created the image we would have to have a whole different jQuery statement, a whole different JavaScript statement in which we’re using jQuery to do this add class operation for example. It really comes down to what you’re trying to have chainable methods for. Toggle that, run, and sure enough we have 2 images. We toggle it again. Note here and here we’ve got class special added.

Once again the differences are subtle here between this create something first and select something first. But it all comes down to our ability to chain methods on things and what makes more sense in each situation. That’s also why we have these different options available to us for DOM manipulation.

There are a lot of DOM manipulation methods available to us. Just keep on scrolling. It can be a little actually daunting even at times. There are just a ton of them. What I would suggest you do, and this is kind of what I did when I got started, I just had this page bookmarked and just kind of wrote out what I wanted to have happen. I need to insert these images after each element in this collection so there’s after available. Or let’s say I need to insert each of these images inside of each paragraph. I need to insert them at the end of the paragraph. It’s like that example. Looking here on the left you’ll notice that if you show everything under manipulation, there’s a lot of different sub menus here available for us.

What I just said again repeated is let’s insert images inside of a paragraph let’s say. Starting right there, here’s our DOM insertion inside methods. Then I want to insert those methods at the end of the paragraph. Looking here it’s going to either be append or append to. The difference is going to depend on whether or not I want to create the element first. I want to create the image, add some event behaviors and other things. Then I can use append to at the end to add it to the end of my paragraphs. Or if I wanted to select the paragraph elements first and do other things with the paragraph, I could use a .append method and append the image to the paragraph. The choice is there really just up to you. Keep that page in mind and use that menu to your advantage, and you should be able to pick up on a lot of these methods.

Let’s look at actually removing elements. There’s a couple different ways to do removing and there’s a couple important considerations. First, the most direct way is the .remove method. That does what you think it does. We will still have elements in our jQuery collection once we remove them, but they won’t be on the page anymore. We could technically add them back later, although when we want to add elements back on the page, there’s a better method to do that with typically, and we’ll see that in a few slides. Go ahead and running this. As we would expect our div is now completely empty. Remove as advertised.

Empty, the slight difference here is empty will simply clean out whatever is inside of the element selected. Looking here our selector is a class of empty-me. We’re going to get this div selected here, and then empty will clean out whatever is inside of the div and so the paragraphs should be removed, and indeed they are.

We also have detach. The big difference with the detach is I like to think of detach when I want to do like a cut-and-paste type of operation with an element. I can first detach that element using the detach method here. Then I can reattach that element later using one of our DOM manipulation methods such as insert after here. You’ll notice one thing I didn’t do here, which I should’ve done, which is propend a dollar sign here so that I would know that this is in fact a jQuery object I’m dealing with.

Again, this is completely functional JavaScript. There’s nothing wrong with this, but just this convention it’s something I typically like to do. Go ahead and run this. Notice in our selector here we had only specified to select the first paragraph, so we really add the first one. We detached it and then we inserted it after our element with class detach-ex, which was in fact a div. Notice where the paragraph now lies outside here. That’s due to the use of the insert after method.

Interesting. You would think for a second here, “What’s going to happen if we run this again?” Go ahead and toggle and watch. Appeared nothing, but if you actually look bar was moved, bar was our first paragraph. Now if we ran this any additional time, this selector no longer applies. There are no paragraphs left within our div here. Running this again would be futile. Just some interesting behavior to look at. All very cool stuff.

Can actually also clone elements. Here we’re using the best practice strong tag. I’m kidding. Please don’t use that. UCSS. But it makes for a simple example. We’ve got a strong tag here inside of a div with an idea of clone source. We’re going to call … We’re going to grab that strong tag, we’re going to clone it, and then append it within our drop area here, this drop here class div. Just go ahead and run that. Note here it’s been cloned and dropped in. If we run it again, once again another strong tag within our class drop here.

One really important note with clone. If you clone elements you end up cloning all of the elements within that tree underneath the elements. Let’s say we clone this div here up top with the idea of clone source. We clone that element, and we clone the strong underneath of it, so you’d have that whole structure cloned. But cloning this element can lead to unintended behavior, because if we clone anything with an identifier and we then place that clone back on the page we now have 2 elements with the same identifier.

Something to be careful about generally with cloning is if you have a lot of IDs on your page cloning can get very tricky and you could end up with a lot of duplicate IDs in your page. There’s ways to get around that in JavaScript. We don’t need to talk about those here. It’s more important that you realize that that problem might occur and just be on the lookout for it in the future.

Let’s go ahead and take these manipulations and apply them. This picture really looks like one of those motivational posters that are oh so awesome in office buildings. In that vein let’s apply ourselves. Take a look at the exercise and come on back to us when you finished up looking at it and we’ll take a look at this solution.