简体   繁体   中英

jQuery: Can't select just appended element

This is what happens on event:

$('div#pages').append($('<div class="page" id="test">...</div>'));

And then, on another event it fails doing this:

var page = $('div.page#test'); // returns empty array

I've debugged, and the appended html appears in the document structure after appending, but fails to get selected. Doing the same in browser console works perfectly.
What could be the problem?

使用.find() http://api.jquery.com/find

var page = $('div#pages').find('div.page#test');

You just need to use live method:

$('.element').live('click', function(){
   alert($(this).html());
});

This is my solution that works fine for appended elements. 在此处输入图片说明

Had the same issue, found that if I added the listener before adding the div, it wouldn't find the div. Make sure to add the listener after making the object.

I had to use a hack to get around this problem recently when I was dynamically inserting <select> elements. I changed this:

var $item = $('#appendedItem1'); // returns: []

to this:

var $item = $(document.getElementById('appendedItem1')); // returns: [select#appendedItem1]

I know it seems like it should be the exact same thing, but only the second one works.

This happens to me a lot more often than I would like. I've tried just about everything and while some solutions work in certain scenarios or browsers, they don't work in others. Some of the most common solutions I've tried were:

Waiting for DOM / element to be ready before selecting or manipulating it (this is so simple but actually works a lot of the time):

$('#element').ready(() => {
    // Get or modify element
});

Using find (see CRABOLO's answer). Here is another example:

// Create element
let div = $('<div></div>');
// Use element to find child
let child = div.find('#element');
// Or
let child = $('#element', div);

If you're trying to listen to events triggered by an appended element, on should work for you most of the time since it can trigger for all future elements matching a selector (see Md Shahriar's answer). Here is another example:

$(document).on('event', '.element', function() {
    // "event" has been triggered on a ".element"
});

And an example from the documentation :

$("body").on("click", "p", function() {
    alert($(this).text());
});

If none of the other solutions work for you , you can always try to check manually using an Interval . This is the only way I've been able to solve this issue in certain situations:

/* Usage:
   onEditable('#element', () => {
       // Element is now for sure ready to be selected or modified.
   });
*/
function onEditable(selector, callback){
    if($(selector)[0]){
        callback();
        return;
    }

    let s = setInterval(() => {
        // Check if jQuery can find the element
        if($(selector)[0]){
            // Call callback function
            clearInterval(s);
            callback();
        }
    }, 20);
}

I can't stress this enough; if you can find another solution that works for you, use that instead, since this doesn't work based on events and takes up a lot more computer resources.

Hope this helps someone having the same issues I did :).

missed quotes on class name page

Also missed ) for append()

Should be

    $('div#pages').append($('<div class="page" id="test">...</div>'));

instead of

$('div#pages').append($('<div class=page id="test">...</div>');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM