简体   繁体   中英

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>

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>

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>

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM