Sam
Sam

Reputation: 591

Append HTML After 2nd Paragraph of Text Using jQuery

Using HTML like this :

<div class="content">
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <p>Paragraph 3</p>
</div> 

With jQuery like this which appends the Click Here HTML after the 1st paragraph :

var $this = $(this);

$this.append('<div id="link" class="link">Click Here/div>');

However, what i need is to append the HTML after the 2nd paragraph using p:nth-child(2) from this answer

Tried the following but doesn't work :

$this('.content p:nth-child(2)').append('<div id="link" class="link">Click Here</div>');

Edit :

 $('.content').each(function() {

    var $this = $(this);

    $this.append('<div id="link" class="link">Click Here</div>');

    $this.children('p:not(:first-child)').wrapAll('<div class="text" />');

} 

And wrap all remaining paragraphs in the text div ( which excludes the 1st 2 paragraphs )

Upvotes: 0

Views: 2048

Answers (3)

aslawin
aslawin

Reputation: 1981

I wrote some part of code for demonstration. Check out this code:

$.each($('.content p'), function (index, paragraph) {
    if (index == 1) { //second element
      $(paragraph).append('<div>some text</div>');
    }
});

Working jsFiddle: CLICK!

Upvotes: 0

BenM
BenM

Reputation: 53198

Your selector is incorrect. You need to use after() as follows:

$(function() {

  $('.content').each(function() {
    var $this = $(this);
  
    $this.children('p:nth-child(2)').append('<div id="link" class="link">Click Here</div>');

    $this.children('p:not(:first-child)').wrapAll('<div class="text" />');

  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="content">
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <p>Paragraph 3</p>
</div>

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

I assume that you are looping through the .content elements as there are multiple instances of them. This is not necessary as jQuery will automatically do this for you if the selector contains a collection of elements. You then simply need to call append() to add the content in the required location. Try this:

$('.content p:nth-child(2)').append('<div id="link" class="link">Click Here</div>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <p>Paragraph 3</p>
</div> 
<div class="content">
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <p>Paragraph 3</p>
</div>

Upvotes: 0

Related Questions