How to get Element by Id from Another website [clo

2020-06-06 06:57发布

I would like to get the content of div by its ID from another site.

Let's say, I have a site and I want to get everything that is inside of div with the id of "mainbar" from this URL - https://stackoverflow.com/questions

Could you tell me, how to make it with native javascript or jquery?

Thanks in advance.

1条回答
Evening l夕情丶
2楼-- · 2020-06-06 07:58

If you have access to the other site and the Access-Control-Allow-Origin header is present, then jQuery can be used like this:

$.get('https://stackoverflow.com/questions').then(function (html) {
    // Success response
    var $mainbar = $(html).find('#mainbar');
    document.write($mainbar.html());
}, function () {
    // Error response
    document.write('Access denied');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

查看更多
登录 后发表回答