1

I'm running GM_xmlhttpRequest (in a Greasemonkey script) and storing the responseText into a newly created HTML element:

var responseHTML = document.createElement('HTML');
...
onload: function() { responseHTML.innerHTML = response.responseText; }


And then I am trying to find an element in responseHTML:

console.log(responseHTML.getElementsByTagName('div'));
console.log(responseHTML.getElementById('result_0'));


The first works fine, but not the second. Any ideas?

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Moose
  • 23
  • 1
  • 4

3 Answers3

8

Use DOMParser() to convert responseText into a searchable DOM tree.
Also, your attempts to search/use anything derived from responseText, must occur inside the onload function.

Use code like this:

GM_xmlhttpRequest ( {
    ...
    onload:     parseAJAX_ResponseHTML,
    ...
} );

function parseAJAX_ResponseHTML (respObject) {
    var parser      = new DOMParser ();
    var responseDoc = parser.parseFromString (respObject.responseText, "text/html");

    console.log (responseDoc.getElementsByTagName('div'));
    console.log (responseDoc.getElementById('result_0'));
}


Of course, also verify that a node with id result_0 is actually in the returned HTML. (Using Firebug, Wireshark, etc.)

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
  • His code works the same as yours: meaning your code doesn't work for the same reason - getElementById is not a method of HTML element, it is a method of document. – slebetman Nov 20 '12 at 06:14
  • 1
    @slebetman: No, my code does work and responseDoc **is** a document. ... You can see that it works at http://fiddle.jshell.net/UEuKZ/show/. (The code is **Firefox only**, which is okay since this is a `Greasemonkey` question). – Brock Adams Nov 20 '12 at 06:56
  • Ah, missed the greasemonkey tag. Sorry. – slebetman Nov 20 '12 at 06:58
  • Thanks, guys. I tend to eschew the DOMParser 'cause I've had trouble getting it work in the past ^_^ But anyways, I see why it wasn't working now. – Moose Nov 20 '12 at 22:05
4

getElementById is not a method of HTML elements. It is a method of the document node. As such you can't do:

div.getElementById('foo'); // invalid code

You can implement your own function to search the DOM by recursively going through children. On newer browsers you can even use the querySelector method. For minimal development you can use libraries like jQuery or sizzle.js (the query engine behind jQuery).

slebetman
  • 109,858
  • 19
  • 140
  • 171
-1

There is no need to store the response in an element neither use DOMParser()

Just set the responseType to 'document' and the response will be parsed automatically and stored in the responseXML

Example:

var ajax = new XMLHttpRequest();
ajax.open('get','http://www.taringa.net');
ajax.responseType = 'document';
ajax.onload = function(){
    console.log(ajax.responseXML); //And this is a document which may execute getElementById
};
ajax.send();
jscripter
  • 840
  • 1
  • 11
  • 23