This really depends on the exact html structure you have. Ideally I would put the 'ul' and it's related 'a' within the same div. But if you have it exactly like in the example above, this will work:
$('a.additem').click(function() { var list_id = $(this).prev('ul').eq(0).attr('id') $('#'+list_id).append('<li>data</li>'); }); Look for 'prev' and 'eq' in documentation, to understand exactly why/ how it works On Jan 14, 9:47 pm, Shawn <smmcbr...@gmail.com> wrote: > Hi. I'm stuck trying to figure out the jQuery way to code this > functionality I have in my project. > > Below is a stripped down example of what I'm trying to do. When I > click the "Add Item" link below any list, I want to just append a new > element to the end of that list. What I do now is just use an onclick > element for each anchor tag, and call addItem and pass the specific > list_id for that list. The function then dynamically locates that > specific list and appends a new item. > > What I have here works (excuse any typos, I'm writing from memory), > but I'd like to make it cleaner by getting rid of the onclick calls > and just having jQuery bind a function to the "additem" class. I just > can't figure out how to pull in the list_id variable in each case. > > Any ideas? > > ... > function addItem(list_id) { > > $('#list_'+list_id+' > ul').append('<li>data</li>'); > return false; > > } > > ... > <ul id="list_1"> > <li>data</li> > <li>data</li> > </ul> > <a class="additem" href="#" onclick="addItem(1);return false;">Add > Item</a> > > <ul id="list_2"> > <li>data</li> > <li>data</li> > </ul> > <a class="additem" href="#" onclick="addItem(2);return false;">Add > Item</a> > ...