How to get Element by Id from Another website [closed]

亡梦爱人 提交于 2020-05-10 06:52:20

问题


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:


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>


来源:https://stackoverflow.com/questions/44369302/how-to-get-element-by-id-from-another-website

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