robert2000
robert2000

Reputation: 1

Fire jQuery event on tag generated by innerHTML

I'm using a javascript loop to create HTML code for a list, Example:

if (thisList.length > 0) {
    var myList = "";
    for (var i = 0; i < thisList.length; i++) {
        myList += '<li>Item ' + i + '</li>';
    }

    var myListBox = document.getElementById('my-list').innerHTML = myList;
}

I am then inserting the HTML code using:

<ul id="my-list" ></ul>

So the rendered HTML would be similar to:

<ul id="my-list" >
    <li>Item 0</li>
    <li>Item 1</li>
</ul>

My Problem: I cannot fire a jQuery event on the tags inside ul#my-list. For example, the following jQuery code has no affect on the li tags.

$(document).ready(function(){
    $('li').click(function() {
        $(this).hide();
});

How can I fire a jQuery event on those tags? Thanks in advance.

Upvotes: 0

Views: 88

Answers (2)

dbarnes
dbarnes

Reputation: 1833

The problem is your bind function is happening before the element is rendered so jquery has nothing to bind to. You need a better way like checking when the li is clicked from my-list node.

If you look at

$(document).ready(function(){
    $('li') //this will have length 0 since the elements are not in the DOM tree yet.
});

You're looking for https://api.jquery.com/on/

$(function(){
    $('#my-list').on('click', 'li',function() {
        $(this).hide();
    });
});

the $(function(){}) is short hand for $(document).ready

Upvotes: 5

Pavel P&#225;ja Halbich
Pavel P&#225;ja Halbich

Reputation: 1583

This is because at document.ready time, your DOM is not completed - you are changing it in runtime. Modify your code in this way:

var myListBox = document.getElementById('my-list').innerHTML = myList;
$('li', myListBox ).click(function() {
    $(this).hide();

Now, after you created DOM, function onClick will bind.

Upvotes: 3

Related Questions