Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery can't find the html elements just appened

I've got following html code:

<div id='list'>
  <ul></ul>
</div>

And I have following jQuery script:

function append_list(){
  $('ul').append('<li><input type="image" name="original" value="'+SOMEVALUE+'"></li>');
}

function find_input(){
  //some code to find the just appended input element.
}

$(document).ready(function(){
  append_list();
  console.log($('input'));
  find_input();
});

And when I look into my browser console, the output of console.log was just an empty array "[]", But if I input console.log($('input')); in my browser console after page loaded, it can feedback with correct data... Did I do anything bad with .append() function?

Thank you for your help.

----EDIT----
Thanks guys, I'd like to add something to my question. I've tried your suggestion to setTimeout(); but still can't find input element I've appended. I've also add console.log($('input)); into function append_list(); also no help... Now I'm stacked here :-(

like image 520
Daniel Chen Avatar asked Dec 05 '25 15:12

Daniel Chen


1 Answers

You should setup a callback function.

Check out: http://jsfiddle.net/bryandowning/4mS9L/

function append_list(someval, callback){

    //save a reference to the element you are appending
    var $element = $('<li><input type="text" name="original" value="'+someval+'"></li>');

    //append it to the list
    $('ul').append($element);

    //if a callback function was provided, execute it.        
    if(arguments.length === 2){
        //pass the callback function the saved reference to the appended element
        callback($element);   
    }
}

//this is the callback function
function find_input(item){
    var $input = item.find("input");

    $input.after("The value of the input element is: " + $input.val());
}

$(document).ready(function(){
    //example with the callback provided
    append_list("First Element", find_input);

    //example without the callback provided
    append_list("Second Element");

});
like image 106
Bryan Downing Avatar answered Dec 08 '25 03:12

Bryan Downing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!