Reputation: 1975
I have the following dom :
<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
<div class="test">4</div>
I would like to add before the nth test element a new element.
I am able to add a new element for all the test element with this code :
var newElement = "div class=\"test-new\"";
$(".test").before(newElement);
But I am not able to select only the desired element thanks to an index(example : 3), these 2 codes throws an error :
var newElement = "div class=\"test-new\"";
$(".test")(3).before(newElement);
$(".test")[3].before(newElement);
Upvotes: 1
Views: 4387
Reputation: 3360
Use this, should work like a charm :)
$(".test:nth-child(3)").before("<div>new item</div>");
Upvotes: 1
Reputation: 4820
use the eq
selector in jquery
var newElement = "div class=\"test-new\"";
$(".test:eq(3)").before(newElement);
you should note, the newElement
needs to be valid html, so you may want to change it to
var newElement = "<div class=\"test-new\"></div>";
$(".test:eq(3)").before(newElement);
fiddle http://jsfiddle.net/0qeh1rL1/
Upvotes: 0
Reputation: 5309
Try something like this:
HTML
<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
<div class="test">4</div>
Jquery
$( ".test:nth-child(2)" ).append( "<div>newtest</div>" );
OUTPUT
1
2
newtest
3
4
Upvotes: 0
Reputation: 33880
There is a function to select an element by index and still keep it as a jQuery object. This function is .eq()
:
$(".test").eq(3).before(newElement);
It is 0 based index, so 3
select the 4th element.
You should also wrap var newElement = "div class=\"test-new\"";
between <
and >
to make a valid element:
var newElement = "<div class=\"test-new\">";
jQuery will interpret this as a new Node instead of a selector.
Upvotes: 1
Reputation: 87233
Use insertBefore:
$('<div />').addClass('test-new').insertBefore('.test');
To insert the element before n-th element use eq:
$('<div />').addClass('test-new').insertBefore($('.test').eq(0));
// Insert before first .test element
$('<div />').addClass('test-new').insertBefore($('.test').eq(3));
// Insert before third .test element
The eq
index starts from zero.
Reduce the set of matched elements to the one at the specified index.
Upvotes: 1
Reputation: 5935
Yes you cannot use the array syntax directly. You can do somethig like this:
$($(".test").get(3)).before(newElement);
Please note the double dollar "$($(" this is necessary because the result of get() it's a DOM element not a jQuery element so you need to pass it to jQuery to use jQuery methods
Upvotes: 0