- Overview
- Transcript
2.7 Creating and Appending Content
In today’s lesson, we’ll review jQuery’s various methods that allow us to add content to the DOM. We’ll make use of append
, prepend
, insertAfter
, insertBefore
, after
, and before
.
Near the conclusion of the video, we’ll build a simple utility script that dynamically creates callouts in a blog posting.
1.Introduction1 lesson, 00:38
1.1Welcome00:38
2.The Basics7 lessons, 1:33:04
2.1Hello jQuery10:52
2.2Not So Fast, jQuery06:54
2.3The Basics of Querying the DOM15:21
2.4Events 10119:58
2.5Events 20115:21
2.6Bind...Live...Delegate...Huh?10:49
2.7Creating and Appending Content13:49
3.Effects9 lessons, 2:39:59
3.1Slides and Structure23:46
3.2The this Keyword09:35
3.3Modifying Effect Speeds05:47
3.4Creating Custom Effect Methods07:16
3.5Full Control With animate21:34
3.6Homework Solutions12:15
3.7The Obligatory Slider (First Attempt)32:50
3.8Prototypal Inheritance and Refactoring the Slider34:03
3.9Your Questions Answered12:53
4.Utilities4 lessons, 59:31
4.1$.each and Templating12:49
4.2Say Hello to Handlebars15:09
4.3The Twitter API22:11
4.4Filtering with jQuery.grep09:22
5.Custom Events1 lesson, 25:17
5.1Custom Events and the Observer Pattern25:17
6.AJAX5 lessons, 1:33:13
6.1Loading Pages Asynchronously11:10
6.2Interacting with the Server-Side11:24
6.3PHP and jQuery: Part 122:37
6.4PHP and jQuery: Part 228:30
6.5Deferreds19:32
7.Plugin Development1 lesson, 45:57
7.1Head First Into Plugin Development45:57
8.Exit1 lesson, 01:06
8.1Goodbye01:06
2.7 Creating and Appending Content
[NOISE] Welcome back to 30 Days to Learn jQuery, and in this lesson we're going to be taking a look at the process and the various methods we can use to add content to the dom. So maybe you have a HTML fragment and you need to insert that at a specific point on your page. Well jQuery offers a handful of different methods to accomplish this. So we will take a look at a bunch of different options today. I'm within my lesson-7 folder and you can see I have a mock-up of a blog posting. There's an article, an h1 and a couple paragraphs just so we have something to work with. And if I open this up in Chrome. Pretty much what you would expect. The first method we're going to take a look at is append. So we begin by fetching the element. We're going to get the article and I want to append for now just a simple string. And to do that, we use the append method. Article.append Hello from the JavaScript. All right, let's try that out. Refresh, and there we go. That's been appended. Easy enough. Now what if we want that text to be placed at the very top of the article's content, rather than the bottom? Well in that case, rather than using append, we use prepend. One more time, refresh, and now that's been placed at the top of the article. Okay, so these are helpful. We have append and prepend. Now what if there's a specific point, maybe we don't want it at the top of the article? We want it placed after the h1 tag. And this is where jQuery is quite nice. The way you would speak it is the way you would use it. So if you want the content to be placed after the h1, then we say hey jQuery, go get the h1 element, wrap it in jQuery. And after it can you add this content for me? All right, one more time and now it's been placed after the h1 tag. Now, the same thing is going to be true for the reverse. If we wanna place it before a paragraph, I could say get the paragraph tag and we'll use a new method. We know we can do nth-child or eq. But there's also helper methods like first. And that means get the very first paragraph tag you find. And now we're going to say before that, we're going to display this text. Now in this case when we refresh the page, it's going to be in the exact same spot. But this time we are grabbing this paragraph and we're adding content before it. Whereas in the last case we were grabbing h1 and appending content after it. Okay, so that's append, prepend, after, and before. Now, what if you're beginning with an HTML fragment? And in that case, jQuery offers a different set of methods that are more or less the same. So for example, we're going to create an h2 tag. Now, in the past, a lot of people would do things like this. They would embed an HTML element and place it within a string and then they would say appendTo the article. Let's try that out. And sure enough, it is being placed. But this gets a little sloppy. You wanna be very careful about mixing too much HTML and JavaScript. You may come into situations where it's not possible to get around it but usually there's going to be a better tool for the job. Whether that's templating or simply splitting up the job. For example, what if you also had a class, and it was my class? Look how sloppy that's becoming. And this is JavaScript, this isn't HTML. Well, instead we could say, we're going to create an h2 element, and we've discussed this before, when you pass a selector string, jQuery knows to hunt down that element. However if we actually create an element and we pass HTML tags, jQuery knows, okay, we're going to create these to throw it in the dom and now I can press a comma and pass an object, and this will allow us to provide some more specifics. For example, I can set the text, I can apply a class. And now if I come back, reload the page, it's still there but if we inspect this element, you'll see that we have applied the class and we've set the text and now we're working with a minimal amount of HTML. And we're simply using an object to set its values. We can do the same thing with setting an ID or style. So that's very helpful and it was introduced in J Query 1.4. Now again, just as we have appendTo, we can also do prependTo. And that will place the content at the very top, like so. Now again, what if we wanna do that same thing where we want to place content after the h1 tag? Well that's easy when you're starting with the h1 as your base. But when we are working with the content itself. Rather than using after, that won't work because we're saying after the fragment that hasn't been inserted into the dom. You would say insertAfter and we're going to place that after the h1 tag. Again notice how you would speak it. Here's some content and I want to insert it after the h1 tag. And you may need to be a little more specific so jQuery knows which one you're referring to. Come back, refresh the page and now it's been inserted after. So notice that after and insertAfter do the exact same thing. It's just based upon what you're working with at the beginning. If you're working with an element then you would use after. If you're creating the element then you would use insertAfter. And the same thing is true insertBefore. And this time we'll say pinth-child(3). We're going to get the third paragraph, that is a child of the article and we're going to insert, and I need to make sure that's a capital B. Remember with JavaScript, all lower case is not the same as having one upper case, that will throw an error. So we're going to get this h2 and insert it before that second paragraph. And there you go now you see it right there. Now that we have taken a look at the various methods we can use to add content to the dom, it's also important to know that you can use these to work with content that already exists. So, for example, what if I grabbed the h1 and I simply want to move it? It's up here and for whatever reason I want to place it, actually at the bottom of the content. Well, we fetch the h1 and now I'm going to say appendTo the article. Now we're saying get this and we're going to move it, and we're going to append it to the article which will place it at the bottom. So let's bring this back and try it out, and now, that's actually been moved. And this is something a lot of people don't know. When you call appendTo on something that exists, it's actually being moved. And the same thing is true if we're gonna get the paragraph, and again I'm being very generic here. You may need to use an id or a class. And we're going to say after and after that we're going to say, get the h1. But now what you're going to see here might be a little different than what you would expect. You might be expecting, okay, we're simply going to see essentially this and that's not going to be the case. You're going to see two h1 tags. Let's try it out. There it is, there's two and this is why you need to be as specific as possible. We're getting a collection of paragraph elements. You'll often hear this referred to as a collection. And then we're saying, after each one of those, we are going to append, whatever the first h1 tag that you find is, essentially. Now if you need to be specific, again, you could say nth-child, or first, or you could use eq. So in this case, we'll get the very first paragraph and after it, we're going to place the h1. There we go and now we're only doing it once. Now in this case we can speed things up just a bit. We're telling jQuer, jump into the dom and find the paragraph tags, then we're going to filter that down to the very first one. But then after that we simply want you to append the element that comes right before it, essentially. So if you have that control, rather than starting from scratch and jumping into that pool looking for the h1. You could pass a function. And this is something that jQuery offers with a lot of the methods. You can pass a function and whatever is returned will be used. So in this case, we're going to return get this, wrapped in jQuery and we're going to return the previous element. Let's try that out. Refresh, and now we're getting the exact same effect. We had the first paragraph, and after it we've placed the contents of the h1. Now the same thing is going to be true for using methods like filter. If you need to run a function to determine exactly what you want to filter that content down. Rather than p, for example, filter(':nth-child'). You would simply replace that, and pass an anonymous function so that you can return whatever you need to. It's important to know that. So now that we have a solid grasp of how we can use these, let's do something practical. Let's say we're going to have a section for blockquotes, and those will be the quotes within a blog posting that pop out and they grab your eye, you'll see them in magazines a lot. Well we don't wanna repeat this content. So for example, I'm going to wrap one of these lines within a span. And I'll give it a class of co for call out. And we will assume that this line is something that's important that we want the user to see so we're going to make it much bigger. Now we're going to grab that content and we are going to append it to the dom within a blockquote. This way we don't have the content and the blog quote. We're not having to double up, which isn't good for RSS feeds. We're using the JavaScript to handle that. We begin by first scrapping all of the call out spans in the dom. For now, we're gonna create a variable called co. And we're going to grab all of the span elements that have a class of co. Then I want to filter through each of them and apply a blockquote to their nearest paragraph parent. So we need an easy way to filter through this wrap set, and jQuery makes that easy by using a method called, each. So we're going to say for each one of those in the collection that was returned, we will then grab the nearest parent element, or the closest parent element. So we'll say, get this. This will refer to the span element right here. And we're gonna find the closest parent that is a p element. At this point, we're now selecting this p tag right here. Then we would simply prepend. Hi there. We're gonna hard code this in just to make sure we're on the right track. Refresh the page, and there we go. We have prepended Hi there. So we're on the right track. Now, we actually want to prepend the blockquote, with a text that's equal to this. All right, so let's start from the blockquote creation, jQuery, we're gonna create a block quote this time. We're going to apply some attributes. We'll give it a class of co as well. And we're going to set its text equal to (this).text. Remember, this is going to refer to that span. I can get rid of this cuz we're no longer doing it that way. We've created a blockquote. We've given it a class. We've applied some text to it. Now we're going to say, prependTo the closest p tag. And we could say, (this).closest('p'). But remember at this point, now we're using this twice. So why don't we cache this? Var this equals this. And now rather than creating a new jQuery object every time, we stick with it just once. All right. Let's go through this. We cache this wrapped in the jQuery object. We create a new blockquote element. We apply a class. We give it some text. Equal to the text of the span tag and then, now that we have that new blockquote, we're going to prepend it to the closest paragraph tag to the span. Refresh. There we go. And now that's been prepended. Let's inspect this. There's our span and it's been placed right there. Now we only need to give it some styling. Style, blockquote.co, and we're gonna float this to the right, give it a background color. Set the font size to roughly 2 ems, refresh, and then let's apply a little styling just to make this look a little more realistic. We'll set the margin to auto and a width of 600 on the wrap. There we go, and now we've added nice little blockquote there. If we want to give it a width, why don't we do that as well. Give it a width of 25% and then what I'm gonna do here is stretch this out just so it looks like we have a little bit more content. And I will duplicate this a couple times. Refresh. And the final thing would be maybe to align that text to the center. We will up the width to 35% and align the text to the center. There we go. And that looks good to me. Now remember, what's neat about this is, it will work on all of the spans in your article as long as they have that class. So this time why don't we take this and we'll place it right here. This is a section that we want to have a call out. One more time, reload the page, and it is still going to work as expected. We'll change the text here. Hello from the JavaScript. Reload. And there we go. So this is a practical thing that you could use in your projects right now. This way, you're not doubling up on the quotes. You don't have it in the sentence, and then you also have a call out. You're doing that with JavaScript, which is clean way to go about it. You grab all the spans, if you want to improve performance of it rather than searching the entire page for the span. You could preface it with the article or once you start getting into these more complex selectors, many times it will be much smarter to first grab the article and then find all of the spans that have a class of co. That way we're using this as a context and jQuery doesn't have to dig into its more complicated selector engine which is referred to as sizzle. And I think that's gonna do it for this lesson. Make sure you paid attention. If you need to, go back and watch it again because you will want to remember these methods. Append, prepend, insertAfter, insertBefore, appendTo, prependTo and then before and after. And most of those, again, are doing the exact same thing. It simply depends on what your selector expression is.