Extract part of HTML document in jQuery

前端 未结 5 1615
囚心锁ツ
囚心锁ツ 2020-11-28 09:01

I want to make an AJAX call to an HTML-returning page, extract part of the HTML (using jQuery selectors), and then use that part in my jQuery-based JavaScript.

The A

5条回答
  •  离开以前
    2020-11-28 09:42

    You could create a div and then put the HTML in that, like this…

    var div = $("
    ").html(data);

    ...and then filter the data like this…

    var content = $("#content", div.get(0));
    

    …and then use that.

    This may look dangerous as you're creating an element and putting arbitrary HTML into it, but it's not: anything dangerous (like a script tag) will only be executed when it's inserted into the document. Here, we insert the data into an element, but that element is never put into the document; only if we insert content into the document would anything be inserted, and even then, only anything in content would be inserted.

提交回复
热议问题