Skip to content

Instantly share code, notes, and snippets.

@joelcardinal
Last active April 28, 2016 21:05
Show Gist options
  • Save joelcardinal/806e2af3207b905487250600b13b0da4 to your computer and use it in GitHub Desktop.
Save joelcardinal/806e2af3207b905487250600b13b0da4 to your computer and use it in GitHub Desktop.
Cobbled together some code examples to put together some functions that will retrieve text from a page (via AJAX) by selector
(function(){
// cobbled together some code examples to put together some functions
// that will retrieve text from a page (via AJAX) by selector
var url = 'http://www.cnn.com';
var selector = 'h2';
getPageData(url,selector);
function parsePageData(html,selector){
var es = new DOMParser().parseFromString(html, 'text/html').querySelectorAll(selector);
var textArray = [].slice.call(es).map(function(n){ return n.innerText.trim() });
if(textArray.length){
console.log('Data found!');
console.log(textArray);
}else{
console.log('Sorry nothing found with that selector');
}
}
function getPageData(url,selector){
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
console.log('Page Request Success!');
parsePageData(this.response,selector)
} else {
console.log('We reached our target server, but it returned an error');
}
};
request.onerror = function() {
console.log('There was a connection error of some sort');
};
request.send();
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment