0

When inserting HTML using jQuery, is it better to use .append or .after?

Based on the description used for the jQuery API, they are nearly identical however for someone learning jQuery, its hard to know which is better in this example.

.after Description: Insert content, specified by the parameter, after each element in the set of matched elements.

.append Description: Insert content, specified by the parameter, to the end of each element in the set of matched elements.

Based on the following example, i think .after should be used to add the read more toggle link not .append because its added after all other HTML elements.

$('.content').each(function() {
  var $this = $(this);
  if ($this.children('p').length >= 2) {  
      $this.append('<div id="toggle">Read More</div>');
  }
});


$('.content p:last-child').each(function() {
  var $this = $(this);
  if ($this.children('p').length >= 2) {  
      $this.after('<div id="toggle-2" class="btn">2nd Read More</div>');
  }
});
.content {
    margin-bottom:10px;
}

.content p {
    margin: 0;
}

.content #toggle {
    margin-top: 5px;
    color: red;
}

.content #toggle-2 {
    margin-top: 15px;
    color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="content">
<p>This is an example of a paragraph</p>
<p>This is an example of a paragraph</p>
</div>

<div class="content">
<p>This is an example of a paragraph</p>
</div>

<div class="content">
<p>This is an example of a paragraph</p>
<p>This is an example of a paragraph</p>
<p>This is an example of a paragraph</p>
<p>This is an example of a paragraph</p>
</div>


<div class="content">
<p>This is an example of a paragraph</p>
</div>
Dev
  • 457
  • 6
  • 18
  • *"When inserting HTML using jQuery, is it better to use .append or .after?"* - They don't do the same thing, so it doesn't make sense to say one is "better". You would use whichever one is appropriate for an individual case. *"they are nearly identical"* - Well they both add content, but they add it in different places. Do you want the new content added inside your existing element or after the existing element? It may not seem to make much difference if you're adding a `
    `, but it would definitely matter if you were adding `
  • ` elements to a `
      `, or `` elements to a ``.
– nnnnnn Oct 01 '17 at 00:32
  • I want to add the read more within the content div but after the last paragraph so i think i could use either which i'll add as a edit to the question. – Dev Oct 01 '17 at 00:58