如何从jQuery对象获取特定的html

时间:2015-08-13 14:40:51

标签: javascript jquery html css

我从网站上获取HTML。我想从该页面获取特定的HTML,而不是所有的如何获得它?我试过跟随;

在将数据附加到目标

之前
container.html(data);

我想做data.find('.site-header').html();,然后做container.html(data);

我怎样才能做到这一点?

DEMO

HTML

<div id="target"></div>

脚本

$(function () {
    var container = $('#target');
    var url = 'http://aamirshahzad.net';

    $.getJSON("http://query.yahooapis.com/v1/public/yql?" +
        "q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(url) +
        "%22&format=xml'&callback=?",

    function (data) {
        if (data.results[0]) {
            var data = filterData(data.results[0]);
            container.html(data);
        } else {
            var errormsg = '<p>Error: could not load the page.</p>';
            container.html(errormsg).focus().effect('highlight', {
                color: '#c00'
            }, 1000);
        }
    });

});


function filterData(data) {
    // filter all the nasties out
    // no body tags
    data = data.replace(/<?\/body[^>]*>/g, '');
    // no linebreaks
    data = data.replace(/[\r|\n]+/g, '');
    // no comments
    data = data.replace(/<--[\S\s]*?-->/g, '');
    // no noscript blocks
    data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g, '');
    // no script blocks
    data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g, '');
    // no self closing scripts
    data = data.replace(/<script.*\/>/, '');
    // [... add as needed ...]
    return data;
}

2 个答案:

答案 0 :(得分:2)

很简单;

container.html($(data).find('.site-header'));

答案 1 :(得分:1)

container.html(data);之后添加此行:

container.html(container.find(".site-header"));

Here is your updated JSFiddle