0

In this project I'm working on, I'm using the npm package 'request' and have a code which looks something like this

request({
  url: 'https://www.google.com/'
}, (error, response, body) => {
  // does stuff here
});

Now, request returns a body which is basically a long string of HTML elements which looks like

<!doctype html><html> ... </html>

What I need to do is convert that string into a DOM so that I can use methods such as getElementById() or getElementByClassName() so I can return whatever values those elements contain.

I know there are libraries such as cheerio which does exactly what I need, but as of this moment I can't use those packages yet so I need to try and find a way to implement this with vanilla javascript.

milestrong
  • 237
  • 1
  • 3
  • 10
  • you want the entire string to be inserted as HTML into a DOM element? – Abdul Samad Sep 14 '17 at 07:46
  • I just want to transform it into an element so I can use functions like getElementById() so I can return their values. This is all happening in the server code, so I wouldn't need to display the HTML anyway. – milestrong Sep 14 '17 at 07:47
  • (https://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro) have a look at this. Use regex to extract parts of the HTML – Abdul Samad Sep 14 '17 at 07:57
  • Why can't you use cheerio? Have you tried jsdom? @AbdulSamad That's an awful idea. Might I remind you of [this](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags). – Ben Fortune Sep 14 '17 at 07:59
  • @AbdulSamad thanks, I'll check that out now. – milestrong Sep 14 '17 at 08:00
  • @Ben and why is that so?He explicitly mentions that he wants to use Vanilla JS – Abdul Samad Sep 14 '17 at 08:01
  • @BenFortune Adding new node packages to our project requires asking for permission from our managers and leads, which I've already done. My lead just asked me to try and implement this in vanilla javascript in the meantime, in case permission is denied. – milestrong Sep 14 '17 at 08:01
  • @AbdulSamad The DOM API's do not exist in node, it is not a browser. – Ben Fortune Sep 14 '17 at 08:02
  • Obviously, they don't. He will have to send the data over an API to the browser and the element creation will be done on client side. – Abdul Samad Sep 14 '17 at 08:03

0 Answers0