Finding an element by ID in an AJAX Response with jQuery

杀马特。学长 韩版系。学妹 提交于 2019-11-30 17:09:23

Notice how all of the elements are on the same level? You need to use .filter() to narrow down the current selection to a single element in that selection, .find() will instead look at the descendants of the current selection.

var success =  $($.parseHTML(response)).filter("#success"); 
console.log(success); // div#success

I got a full 'html' page returned by ajax, but I only need partial of its content, which wrapped by a div and also I need to execute the script inside the 'html' page.

 $.ajax ({
  type: "POST",
  url : "contact.php",
  data: $("#formContactUs").serialize(),
  success: function(msg){
    console.log($(msg)); // this would returned as an array
    console.log(msg);    // return whole html page as string '<html><body>...</body></html>'
    $('#id').html($(content).closest('.target-class'));
    $('#id').append($(content).closest('script')[0]);  // append and execute first script found, when there is more than one script.
  }
});

@kevin answer gave hints to why find() is not working as expected, as it only select its descendant but not the first element under consideration. Besides using filter, $.closest() also works if current element is what you are looking for. Well, probably this post quite similar to @Kevin's answer, it's just to suggest another alternative answer and gave more details which hopefully make thing clearer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!