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>
`, or `` elements to a ` `.