views:

32

answers:

3

Hi, I have the following code

    img.after('<li></li>');

Which works correctly and add the "li" element. Now I want to select the "li" element; it doesn't have any class or ID, but I want to select it just after creating it, so I'm able to use it (for example mynewli.addClass()) as a jquery element.

How can I do that?

A: 

use next():

http://api.jquery.com/next/

assuming that img is a JQuery DOM object:

img.next().addClass('whatever');
mamoo
+2  A: 

You can use the next method

img.next();

to find the next sibling of img, which should be your added li element.

Veger
+5  A: 

Use .insertAfter() to be able to chain, which is the heart of jQuery.

var $newLI = $('<li/>').insertAfter(img).addClass('yourclass');

edit

In respect of your comment, use

img.next('li');

onto your cached img element. Note that this won't guarantee that you select a specific element, it'll just select that next li element. So I still suggest to use .insertAfter() and cache that newly created item into a variable, to access later.

Reference: .insertAfter()

jAndy
Good solution, but this won't let me select the item again (only on that chain)
Omar Abid