2

I try to insert list item between list elements:

$('#deals-providers dt').each(function(index) {
        if (index == 10) {          

            $(this).insertBefore($('<dt/>').text('More item'));

        }
});

but it doesn't work. How can I do this?

1
  • How/Where is index updated? Commented Sep 1, 2011 at 11:08

5 Answers 5

2

This does what you want:

$('#deals-providers dt:eq(9)').after('<dt>More item</dt>');

The :eq() selects the item at that index.

JSBin Example

Sign up to request clarification or add additional context in comments.

Comments

2

try this:

edit:

$('dt:nth(10)').before('<dt>More item</dt>');

4 Comments

I don't think you want the [10] there as that gives you the dom element rather than the 11th jQuery object in the collection - jsbin.com/ezopix/2/edit#preview
I try $('#deals-providers dt')[10].insertBefore($('<dt>More</dt>')); too, but all above gives me jQuery error, probably it is old version
@jadept No, it's because it's trying to call insertBefore on the 11th dom element which doesn't have a method called insertBefore.
this works on jsbin for the example of Richard $('dt:nth(10)').before('<dt>More item</dt>');
1

You could also use the :nth-child selector

See: http://jsfiddle.net/L2tk2/1/

Comments

0
$('#deals-providers dt').each(function(index) {
        if (index == 10) {          
            $(this).insertBefore($('dt:contains("More item")'));
        }
});

Comments

0

You can use the jQuery#eq method to return an element at a designated index. This will return a jQuery object, unlike jQuery#get, which returns an element node.

$('#deals-providers dt').eq(10).before(
  $('<dt>').text('More text')
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.