jQuery .find() on data from .ajax() call is returning “[object Object]” instead of div

前端 未结 17 1168
一生所求
一生所求 2020-12-07 22:05

Trying to find div element with id=\"result\" in returned data from .ajax() using .find(). Unfortunately, alert(res

相关标签:
17条回答
  • 2020-12-07 22:39

    Is #result in the response HTML? Try the following. jQuery will still return an empty object if it doesn't find anything.

    alert(result.length);
    
    0 讨论(0)
  • 2020-12-07 22:39

    To view the content in alert use:

    alert( $(response).find("#result").html() );

    0 讨论(0)
  • 2020-12-07 22:41

    this is your answer:

    <div class="test">Hello</div>
    <div class="one">World</div>    
    

    The following jQuery Won't work:

    $(data).find('div.test');    
    

    as the divs are top level elements and data isn't an element but a string, to make it work you need to use .filter

    $(data).filter('div.test');    
    

    Another same question: Use Jquery Selectors on $.AJAX loaded HTML?

    0 讨论(0)
  • 2020-12-07 22:41

    do not forget to do it with parse html. like:

    $.ajax({
        url: url, 
        cache: false,
        success: function(response) {
            var parsed = $.parseHTML(response);
            result = $(parsed).find("#result");
        }
    });
    

    has to work :)

    0 讨论(0)
  • 2020-12-07 22:41

    you just use the following code

    var response= $(result);
    
    $(response).find("#id/.class").html(); [or] $($(result)).find("#id/.class").html();
    
    0 讨论(0)
  • 2020-12-07 22:43

    I just spent 3 hours to solve a similar problem. This is what worked for me.

    The element that I was attempting to retrieve from my $.get response was a first child element of the body tag. For some reason when I wrapped a div around this element, it became retrievable through $(response).find('#nameofelement').

    No idea why but yeah, retrievable element cannot be first child of body... that might be helpful to someone :)

    0 讨论(0)
提交回复
热议问题