JQuery cannot find html elements just added

I have the following html code:

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

And I have the 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 at the browser console, the output of console.log was just an empty array of “[]”, but if I enter console.log ($ ('input')); in my browser console after loading the page, it can receive feedback with the correct data ... I did a bad job with the .append () function?

Thank you for your help.

---- EDIT ----
Thanks guys, I would like to add something to my question. I tried your suggestion setTimeout (); but still can not find the input element that I added. I also add console.log($('input));in function append_list();too without help ... Now I put it here: - (

+3
5

.

: 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");

});
+2

, append_list() console.log..., , , .

:

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

, append_list(), , .

+1

id:

<ul id='myul'></ul>

$('#myul').append(...
0

, ... ""...

append_list();
setTimeout(find_input, 1);
0

It seems that console.log works before the user interface changes are completed, and why it does not find the added elements. If you use setTimout with a 1 ms delay, this will cause the following code to delay until the user interface changes are complete, which should give the correct result.

append_list();
setTimeout(function() {
  console.log($('input'));
  find_input();
}, 1);
0
source

Source: https://habr.com/ru/post/1779313/


All Articles