0

(I'll try to keep the question simple for now, since I don't really know how to go about this.)

I have to change unordered list elements inside an html file by

1.) Create a DOM fragment ( for each of the new <li> ) in javascript.

2.) Remove the original batch of <li> in the ul.

3.) Append each new DOM fragment into the ul

4.) Make each of the new <li> elements clickable again

Clicking on a <li> element removes the contents of the ul and replaces it with a new batch (the batch varies from 0 <li> to 6 <li> elements (depending on which element you clicked))

The first problem I'm having is that there is no way to create multiple elements clickable in one go (for loops doesnt work) so at the moment im just repeating the functions I have.

    $( "#choices" ).children().eq(0).click(function() {
        selectChoice(allChoices, $( "#choices" ).children().eq(0).text());
    });

    $( "#choices" ).children().eq(1).click(function() {
        selectChoice(allChoices, $( "#choices" ).children().eq(1).text());
    });
    // more li elements to make clickable

Second, when you remove a li element and put back a new element, you have to make it clickable, but since you dont know the number of elements and for loops dont work, I can't add a function upon creation. Not all elements follow the same format also, so simply modifying the existing li isnt an option.

Is there a simple way that I don't know about that does what I want it to do..?

1 Answers1

0

You're using jQuery, right?

Look into the on method. You should be able to do something like

$('#choices').on('click', 'li', function(ev) {
   ... do your thing ...
});

As new li's are added under #choices, this event binding will be automatically added to the new li. http://api.jquery.com/on/

mr rogers
  • 3,200
  • 1
  • 19
  • 31
  • _"You're using jQuery, right?"_ - What do you think? – Weafs.py Nov 17 '14 at 00:45
  • If each element in the previous batch opens a new set of differing elements would this still work? Won't the event of one element be same throughout the list? –  Nov 17 '14 at 00:54
  • As long as you don't throw out the container, it should work fine. – mr rogers Nov 17 '14 at 00:59