Dev Dev - 3 years ago 139
HTML Question

Append Div After 1st Paragraph For Each Article When More Than 1 Paragraph

Is it possible to append ( rather than use .after() ) a HTML div after the first paragraph of text for each article only when there's at least 2 paragraphs for each article, otherwise don't add the div?



$('.content').each(function() {
var $this = $(this);
if ($this.children('p').length >= 2) {
$this.append('<div id="toggle">Read More</div>');
$('p').not('p:first-child').wrap('<div class="text" />');
}
});

<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>
</div>





This is what i need to achieve. The divs are only added when there's more than 1 paragraph of text for each content div.

<div class="content">
<p>This is an example of a paragraph</p>
<div class="text" />
<p>This is an example of a paragraph</p>
<div id="toggle">Read More</div>
</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>
<div class="text" />
<p>This is an example of a paragraph</p>
<div id="toggle">Read More</div>
</div>

Answer Source

You were so close!

$('.content').each(function() {
  var $this = $(this);
  if ($this.children('p').length >= 2) {  
      $this.append('<div id="toggle">Read More</div>');
  }
});
.content {
border:1px solid red;
margin-bottom:10px;
}

.content p {
margin:0;
}

.content #toggle {
margin-top:5px;
color:cyan;
}
<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>


<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>
<p>This is an example of a paragraph</p>
<p>This is an example of a paragraph</p>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download