about_robots about_robots - 2 months ago 7
HTML Question

search by class in string javascript

Let's suppose I have this string:



var myhtml= "<html><body><div class='header'>Welcome</div><div class='news' id='new_1'>Lorem ipsum....</div><div class='news' id='new_2'>dolor sit amet...</div></body></html>";





Well, if this was on a normal website I could use "getElementsbyClassName" to get all elements with the class I want to select (In my case, "news").
But... If it's like this case, when you have all the html in a variable, how can I get them? Is there a way to get all the divs with class is "news"?

Answer

You can use cheerio for that:

var cheerio = require('cheerio');

var myhtml = "<html><body><div class='header'>Welcome</div><div       class='news' id='new_1'>Lorem ipsum....</div><div class='news' id='new_2'>dolor sit amet...</div></body></html>";

var $ = cheerio.load(myhtml);

console.log($('.header').html() );//Welcome