[英]How to append an element after specific child element using jquery?
I want to append a paragraph element after specific div class element.我想在特定的 div class 元素之后 append 一个段落元素。
I want to add a p
element inside second text
div
class.我想在第二个
text
div
class 中添加一个p
元素。 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?如何使用 jquery 在第二个文本 div class 中插入这个
p
元素?
$(".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 nth-of-type 这似乎效果更好
$(".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>
$(".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.以防万一您不一定需要 jQuery,您也可以使用带有香草 JS 的 go。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.