Home > Enterprise >  How to append an element after specific child element using jquery?
How to append an element after specific child element using jquery?

Time:01-07

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 >
  <p>First</p>
</div>
<div >
  <p>Second</p>
</div>
<div >
  <p>Third</p>
</div>
<div >
  <p>Fourth</p>
</div>

CodePudding user response:

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 >
  <p>First</p>
</div>
<div >
  <p>Second</p>
</div>
<div >
  <p>Third</p>
</div>
<div >
  <p>Fourth</p>
</div>

CodePudding user response:

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 >
  <p>First</p>
</div>
<div >
  <p>Second</p>
</div>
<div >
  <p>Third</p>
</div>
<div >
  <p>Fourth</p>
</div>

CodePudding user response:

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

CodePudding user response:

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 >
  <p>First</p>
</div>
<div >
  <p>Second</p>
</div>
<div >
  <p>Third</p>
</div>
<div >
  <p>Fourth</p>
</div>
</div>

  •  Tags:  
  • Related