Anurag Mishra
Anurag Mishra

Reputation: 699

How to append an element after specific child element using jquery?

I want to append a paragraph element after specific div class element.

I want to add a p element inside second text div class. I tried a solution but it's not working.

My solution it's not working. How can I insert this p element in second text div class using jquery ?

$(".text:nth-child(2)").append("<p>Five</p>");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="text">
  <p>First</p>
</div>
<div class="text">
  <p>Second</p>
</div>
<div class="text">
  <p>Third</p>
</div>
<div class="text">
  <p>Fourth</p>
</div>

Upvotes: 1

Views: 95

Answers (4)

MWO
MWO

Reputation: 2806

Just in case you don't necessarily need jQuery, you can go with vanilla JS aswell.

var el = [...document.getElementsByClassName("text")][1];
var p = document.createElement("p");
var t = document.createTextNode("Five");
el.appendChild(p.appendChild(t));
<div class="text">
  <p>First</p>
</div>
<div class="text">
  <p>Second</p>
</div>
<div class="text">
  <p>Third</p>
</div>
<div class="text">
  <p>Fourth</p>
</div>
</div>

Upvotes: 0

mplungjan
mplungjan

Reputation: 177684

nth-of-type this seems to work better

$(".text:nth-of-type(2)").append("<p>Five</p>");
.text { border: 1px solid black; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="text">
  <p>First</p>
</div>
<div class="text">
  <p>Second</p>
</div>
<div class="text">
  <p>Third</p>
</div>
<div class="text">
  <p>Fourth</p>
</div>

Upvotes: 2

Tino
Tino

Reputation: 158

$('.text:eq(1)').append("<p>Five</p>");

Upvotes: 0

Kinglish
Kinglish

Reputation: 23654

You can use .eq(n)

$(".text").eq(1).append("<p>Five</p>");
.text {
  padding: 5px;
  margin-bottom: 10px;
  background: #f0f0f0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="text">
  <p>First</p>
</div>
<div class="text">
  <p>Second</p>
</div>
<div class="text">
  <p>Third</p>
</div>
<div class="text">
  <p>Fourth</p>
</div>

Upvotes: 1

Related Questions