Say I have a page a.html and want to retrieve a text element's text using it's id <p id="name">NAME</p> element from another page b.html.
3 Answers
Using jQuery's get method, it's pretty simple:
$.get('a.html', null, function(text){
alert($(text).find('#name'));
});
Raw XHR Request (by popular demand):
var request = new XMLHttpRequest();
request.addEventListener("load", function(evt){
console.log(evt);
}, false);
request.open('GET', 'a.html', true),
request.send();
9 Comments
I Hate Lazy
jQuery has no
$.load method, and it's overkill to load a large library just to do a simple XHR request.Alex
@user1689607 really?! is it overkill if the client's browser has jQuery already in its cache?
I Hate Lazy
@Xander: How do you know if it's in the cache?
I Hate Lazy
Absolutely, if OP has other uses, then it may be worth the download, but I wouldn't be too quick to assume there's such a high probability of being cached. Again, each CDN hosts dozens of versions. There are plenty of sites that use one of the old (and maybe even one of the unminified) versions. So it's really hit or miss.
|
You need to:
- Fetch the content of the page (you imply that Same Origin Policy won't be a problem, so I won't discuss working around that).
- Parse that into an HTML DOM
- Extract the part of that DOM you care about
- Do something with that DOM
This is quite a lot of work. jQuery will do most of the work for you:
jQuery('#element_to_load_content_into').load('a.html#name'); // Note use of fragment identifier
3 Comments
Quentin
@PrathameshDoke — Nothing has fundamentally changed since I wrote this answer.
Shayan
This "loads" a webpage partially, I see that a lot of body elements do not exist in the element I loaded the content into. Any idea how to make it load everything?
Quentin
@Shayan — I've no idea what you are doing or to what data. Try asking a new question, with an minimal reproducible example and reference this for context.
iframe, then get the element. But wouldn't you rather just have the server return the data you want?