ofir_aghai
ofir_aghai

Reputation: 3321

jquery select section by it's own index

How can i select the third section, and add new section before it?

Before:

<article id="container">
    <section> a </section>
    <section> b </section>
    <section> d </section>
    <section> e </section>
</article>

After:

<article id="container">
    <section> a </section>
    <section> b </section>
    <section> c </section>
    <section> d </section>
    <section> e </section>
</article>

Upvotes: 1

Views: 1385

Answers (4)

Gildas.Tambo
Gildas.Tambo

Reputation: 22653

Use Node.insertBefore() and :nth-child - CSS to select the third section.

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

Upvotes: 0

PeterKA
PeterKA

Reputation: 24638

You can use $( target ).before( content ) or $( content ).insertBefore( target ) as shown below:

$('<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>

Upvotes: 1

Adil Shaikh
Adil Shaikh

Reputation: 44740

Using eq

$newSection = $("<section>c</section>");
$("#container section").eq(2).before($newSection);

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

Demo --> https://jsfiddle.net/2f7n1r06/1/

Upvotes: 2

Milind Anantwar
Milind Anantwar

Reputation: 82241

You can use .after() selector:

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

Working Demo

Upvotes: 2

Related Questions