riki
riki

Reputation: 2393

Not able to perform click event on dynamically created html elements

I'm using jquery and creating some ul, li and a dynamically on $('document').ready(). After this the ul-li renders in browser is looks like bellow in html representation

                    <ul class="ul">
                        <li class="li">
                            <a>Some buddy</a>
                            <ul class="ul">
                                <li class="li" id="testLi">
                                    <a id="testView">test buddy</a>
                                </li>
                            </ul>
                        </li>
                    </ul>

Please ignore class names. I have assigned ids to <li> and child` tags. and I also have a function written as bellow:

$(document).ready(function () {
    $('#testView').click(function () {
        var ul = document.createElement('ul');
        ul.className = 'ul';

         var li = document.createElement('li');
         li.className = 'li';
         var a = document.createElement('a');
         a.innerHTML = 'test buddy';
         $(li).append(a);
         $(ul).append(li);

        $('#testLi').append(ul);
    });
});

Now if I click on <a id="testView">test buddy</a> my function does not get called. I think this because DOM is loaded and my new elements are get created in ready(). Please provide a solution.

Upvotes: 0

Views: 150

Answers (2)

haxtbh
haxtbh

Reputation: 3534

You will need to attach the event handler to the document and delegate the event to the element.

You can do something like this:

    $(document).on('click', '#testView', function () {
        var ul = document.createElement('ul');
        ul.className = 'ul';

         var li = document.createElement('li');
         li.className = 'li';
         var a = document.createElement('a');
         a.innerHTML = 'test buddy';
         $(li).append(a);
         $(ul).append(li);

        $('#testLi').append(ul);
    });

This will apply to all the elements with this id regardless of whether they are created before document.ready() or not.

Upvotes: 3

Tony_89
Tony_89

Reputation: 817

Your code is working fine. I have added it to the snippet below.

$(document).ready(function() {
  $('#testView').click(function() {
    var ul = document.createElement('ul');
    ul.className = 'ul';

    var li = document.createElement('li');
    li.className = 'li';
    var a = document.createElement('a');
    a.innerHTML = 'test buddy';
    $(li).append(a);
    $(ul).append(li);

    $('#testLi').append(ul);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="ul">
  <li class="li">
    <a>Some buddy</a>
    <ul class="ul">
      <li class="li" id="testLi">
        <a id="testView">test buddy</a>
      </li>
    </ul>
  </li>
</ul>

Upvotes: -1

Related Questions