Noah Noah - 1 year ago 101
Javascript Question

Parse GET request string as HTML

I used a GET request to get the HTML on another page with Javascript and that worked fine but now I need to get a certain class which I could normally do like this:


but now I can't do it because it is just normal text. Is there a way I can parse this?

Answer Source

With your HTML as a string called htmlString, you can create a DOM element and then parse it.

var htmlElem = document.createElement("html");
htmlElem.innerHTML = htmlString;

// now perform getElementsByClassName() on htmlElem, not document


With jQuery, this is even easier. Just use $.parseHTML():

// $.parseHTML() returns DOM nodes; wrap it in jQuery wrapper to get jQuery object
var htmlElem = $($.parseHTML(htmlString));

// now do what you need


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