How to fetch a specific div using Javascript in Zapier?

I am utilizing a Javascript step within Zapier to retrieve HTML content from a specified URL, as demonstrated below:

fetch('http://example.com') //sample URL
  .then(function(response) {
    return response.text();
  })
  .then(function(htmlContent) {
    var result = {id: 5678, extractedHTML: htmlContent};
    callback(null, result);
  })
  .catch(callback);

This approach is effective, but I only need content from a certain section rather than the entire HTML body.

Is there a way to retrieve the HTML specifically from a div class, like PrintButtons, instead of the complete document?

To extract a specific div, you can leverage DOM parsing techniques. After fetching the HTML content, you can convert it into a DOM structure which allows you to access elements like you would in a browser. Here’s a simple way to achieve this using a DOM parser:

fetch('http://example.com')
  .then(response => response.text())
  .then(htmlContent => {
    const parser = new DOMParser();
    const doc = parser.parseFromString(htmlContent, 'text/html');
    const targetDiv = doc.querySelector('.PrintButtons');
    const result = {id: 5678, extractedHTML: targetDiv.innerHTML};
    callback(null, result);
  })
  .catch(callback);

This method uses the DOMParser API to convert the string to an HTMLDocument, allowing you to search for elements using querySelector and extract the inner content of the desired div.