Ante Dražić Ante Dražić - 1 year ago 138
Javascript Question

Using getElementsByName for plain text in xhr.responseText

I'm doing XMLHttpRequest on site that doesn't have the official API and I'm receiving HTML response in

. However, I can't do
to extract a value of specific element called "something".

I can open a new window and use document.write to write
on that window and then use
but I'm not going that way.

Problematic part of my code:


Answer Source

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).


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download