2

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?

Jonathan Lam
  • 16,831
  • 17
  • 68
  • 94
Noah
  • 120
  • 1
  • 8
  • Possible duplicate of [Parse a HTML String with JS](http://stackoverflow.com/questions/10585029/parse-a-html-string-with-js) – Jonathan Lam Aug 23 '16 at 15:15
  • Welcome to SO. Please visit the [help] to see how and what to ask. In this case give us a minimum amount of input and code to understand what you are trying to do – mplungjan Aug 23 '16 at 15:16

1 Answers1

2

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

Jonathan Lam
  • 16,831
  • 17
  • 68
  • 94