如何选择第三部分,并在其之前添加新部分?
之前:
<article id="container">
<section> a </section>
<section> b </section>
<section> d </section>
<section> e </section>
</article>
后:
<article id="container">
<section> a </section>
<section> b </section>
<section> c </section>
<section> d </section>
<section> e </section>
</article>
答案 0 :(得分:2)
您可以使用.after()
选择器:
$("#container section:eq(1)").after($("<section>cc</section>"));
<强> Working Demo 强>
答案 1 :(得分:2)
使用eq
$newSection = $("<section>c</section>");
$("#container section").eq(2).before($newSection);
答案 2 :(得分:1)
您可以使用$( target ).before( content )或$( content ).insertBefore( target ),如下所示:
$('<section> c </section>').insertBefore('#container > section:eq(2)');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<article id="container">
<section> a </section>
<section> b </section>
<section> d </section>
<section> e </section>
</article>
答案 3 :(得分:0)
使用Node.insertBefore()和:nth-child - CSS选择第三部分。
// Create a new, plain <section> element
var sp1 = document.createElement("section");
sp1.innerHTML ="c";
// Get a reference to the element, before we want to insert the element
var sp2 = document.querySelector("#container section:nth-child(3)");//he third section
// Get a reference to the parent element
var parentDiv = sp2.parentNode;
// Insert the new element into the DOM before sp2
parentDiv.insertBefore(sp1, sp2);
<article id="container">
<section> a </section>
<section> b </section>
<section> d </section>
<section> e </section>
</article>