Reputation: 33
I'm doing XMLHttpRequest on site that doesn't have the official API and I'm receiving HTML response in xhr.responseText
. However, I can't do xhr.responseText.getElementsByName("something")[0].value;
to extract a value of specific element called "something".
I can open a new window and use document.write to write xhr.responseText
on that window and then use window_name.getElementsByName("something")[0].value;
but I'm not going that way.
Problematic part of my code:
xhr.responseText.getElementsByName("something")[0].value;
Upvotes: 0
Views: 763
Reputation: 22637
You can use the DOMParser API in those browsers that support it:
var parser = new DOMParser();
var doc = parser.parseFromString(xhr.responseText, "text/html");
Now doc
is a HTMLDocument
object, with getElementsByName
and all.
Available in IE9+ and other standard browsers (IE10 for HTML documents, not available in Safari).
Alternative
You can create HTML documents without the need of a new window/frame too:
doc = document.implementation.createHTMLDocument("");
doc.documentElement.innerHTML = xhr.responseText;
This should be available in IE9 and Safari too.
Upvotes: 1