Home > database >  Can I scrapping an HTML code snippet on browser
Can I scrapping an HTML code snippet on browser

Time:12-07

I have an HTML code block. How can I scrapping on browser this snippet with pure JS or JQuery?

Here is my code:

<ul>
    <li>New York</li>
    <li>London</li>
    <li>Madrid</li>
    <li>Paris</li>
</ul>

The result I expected is:

<p>New York, London, Madrid, Paris</p>

I don't need to get a website's HTML document. I already have many blocks. I just want to client-side scrap these blocks.

CodePudding user response:

If I understood you correctly you already have a string containing the HTML so the only thing you need is to parse that string. This can be done using the DOMParser class. From then on it's straightforward because you get a Document returned which offers all the methods you should already now from the DOM of a webpage. In this case you can use getElementsByTagName() to get all the list items and then use map() to only get the textContent those list items.

const domParser = new DOMParser();
const parsed = domParser.parseFromString(`
<ul>
  <li>New York</li>
  <li>London</li>
  <li>Madrid</li>
  <li>Paris</li>
</ul>`, "text/html");

const cityArray = [...parsed.getElementsByTagName("li")].map(li => li.textContent);
console.log(cityArray);

CodePudding user response:

Here is one way, see snippet below with comments:

// get all of the list items
var cities = document.querySelectorAll('li');
// create an empty string to hold the output
var output = '';

// loop through the list items
for (var i = 0; i < cities.length; i  ) {
  // add the text from each list item to the output string
  output  = cities[i].innerText   ', ';
}

// create a p tag
var p = document.createElement('p');
// set the text of the p tag to the output string, removing the last comma
p.textContent = output.slice(0, -2);
// append the p tag to the page
document.body.appendChild(p);
// log p to console
console.log(p)
<ul>
  <li>New York</li>
  <li>London</li>
  <li>Madrid</li>
  <li>Paris</li>
</ul>

  • Related