GHOST-34 GHOST-34 - 1 year ago 74
HTML Question

Not sure why jQuery find() method is not working

Okay, I thought I was better than this, but I've done everything I can. I've got a simple task manager webapp. I want to set the 'checked' attribute of a checkbox input field to 'true' when the status property of my task object is 'true' after a successful get request.

Before I do this however, I inject my dynamic html using the Mustache.js template engine by calling a helper function. I created a callback function that will execute once the html is injected to avoid searching for nothing when I go to mark 'checked' to 'true'. That all looks like this:



// AJAX call for getting current tasks
url: '/tasks',
type: 'GET'
}).done(function(response, textStatus, jqXHR){
$.each($.parseJSON(response), function(i, task){
insertTask(task, function(){
if (task.status == true){
console.log("Task with status of 'true': ");
console.log("Below should be the checkbox");
console.log($('body').find($('#' +;
$('#tasks').find($('#' +'checked', true);

Template handler:

// Uses the mustache template engine to dynamically insert tasks into DOM
function insertTask(data, callback){
$.Mustache.load('templates/tasks.html', function() {
$('#tasks').mustache('main_form', data);
if (callback && typeof(callback) == 'function'){


When I do
console.log($('#tasks').find('#' +;
all I get back is the #tasks object. Even if I just search for an 'li' it returns the #task object. So obviously this sounds like the html just hasn't been injected yet. But I don't see how that's possible given that I have the callback function.

UPDATE: I threw some test classes in the html template to see what is and is not showing up if I search for it and it appears as though the html template STILL does not load even after the $.each loop finished. I searched for the test classes in other handlers (delete and another put) and was successfully able to retrieve them. Could the template engine be slow? Would it even matter with the callbacks?

Answer Source

The id of your checkbox is like 2a49....

Your selector is $('#tasks').find($('#task_' +'checked', true);

It compiles to

>>$('#tasks #task_2a49....

which won't return anything as it tries to find element with id = task_2a49.....

Just use,


Put your call to callback() inside the .load(). The callback was being triggered before load() returned results.

$.Mustache.load('templates/tasks.html', function() {
    $('#tasks').mustache('main_form', data);

    if (callback && typeof(callback) == 'function'){