jquery按照自己的索引选择部分

时间:2015-05-19 14:34:57

标签: javascript jquery html

如何选择第三部分,并在其之前添加新部分?

之前:

<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>

4 个答案:

答案 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);

http://api.jquery.com/before/https://api.jquery.com/eq/

演示--> https://jsfiddle.net/2f7n1r06/1/

答案 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>