devs
devs

Reputation: 541

Looping through generated HTML with jQuery

I know if I wanted to bind events to generated HTML, I'd need to use something like .on(), but I've only used it when binding events like .click().

I'm creating a web app that applys a list of colors. Colors are generated from a JSON file. Once fetched, I add it to the page, with certain information contained in attributes. I'd like to do something with the new generated HTML, which is list-elements. But what console.log() is showing me is there is nothing in the parent ul. Even though on the page I see the newly added content.

Here's the entire code based around it.

var setColors = function(){

    getColors = function(){
        $.getJSON('js/colors.json', function(colors) {
                $.each(colors, function(i, colors) {
                //console.log(colors);
                    $('<li>', {
                        text: colors['color'],
                        'name' : colors['color'],
                        'data-hex' : colors['hex'],
                        'data-var' : colors['var']
                    }).appendTo('#picker');
                })
        });

        addColors();
    }

    addColors = function(){
        var el = $('#picker').children;
        $(el).each(function(){
            console.log($(this));
        });
    }

    return getColors();
}


$(function(){

    setColors();

});

addColors() is where I'm having trouble with. The error says 'Uncaught TypeError: Cannot read property 'firstChild' of null. How can I work with the newly generated HTML?

Upvotes: 0

Views: 76

Answers (2)

vol7ron
vol7ron

Reputation: 42099

addColors = function(){
    var el = $('#picker').children;
    $(el).each(function(){
        console.log($(this));
    });
}

A few issues:

  1. missing end semi-color
  2. missing parentheses on .children()
  3. children() returns a jQuery object, no need for $(el)

Updated:

window.addColors = function(){
    var $el = $('#picker').children();
    $el.each(function(){
        // do stuff here, but could attach each() to above, after children()
    });
};

Upvotes: 0

Justin Bicknell
Justin Bicknell

Reputation: 4798

You are missing parentheses on the children method:

var el = $('#picker').children();

Also, if you want the addColor method to be executed on the newly generated html, then you must add a call to it after the html is generated, from within the getJSON callback method.

Upvotes: 3

Related Questions