2015-05-19 41 views
1

我怎樣才能選擇第三部分,並在它之前添加新的部分?jquery select section by it's own index

前:

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

回答

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>

+0

非常感謝你! –

+0

嘿它真的工作! –

+0

不客氣。很高興我能幫上忙。 :) – PeterKA

2

您可以使用.after()選擇:

$("#container section:eq(1)").after($("<section>cc</section>")); 

Working Demo

+1

嗯,這在技術上不正確的。他希望在**第三個**元素之前添加一個新的部分**。因此'$(「#article section:eq(2)」)。before($(「

cc Markai

+0

第三個元素之後不是指第二個元素之後? –

+0

如果它們之間存在任何東西,比如div或任何其他東西 – Markai

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>

+0

謝謝你的男人!但我得到縮短解決方案:) –