Noah Noah - 3 months ago 14
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:

document.getElementsByClassName("class");




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

Answer

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
htmlElem.getElementsByClassName("class");

Demo


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
htmlElem.find(".class");

Demo

Comments