Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Javascript to access another page's elements?

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.

like image 307
Jeremy Avatar asked Oct 15 '12 15:10

Jeremy


2 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();
like image 54
Alex Avatar answered Sep 21 '22 09:09

Alex


You need to:

  1. 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).
  2. Parse that into an HTML DOM
  3. Extract the part of that DOM you care about
  4. 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
like image 45
Quentin Avatar answered Sep 21 '22 09:09

Quentin