I am in need of creating a specialized Gulp task that can effectively strip out attributes from my HTML code

I am in need of a Gulp task that can iterate through all specified HTML documents and eliminate specific attributes (such as style=""). I initially attempted to accomplish this task the same way I would do it via the browser, but it seems that's not possible. Here is my proposed solution:

// Define a function to remove multiple attributes from an element
const discardAttributes = (element, ...attributes) =>
  attributes.forEach((attribute) => element.removeAttribute(attribute));

// Apply the function to various elements
document.querySelectorAll("table, thead, tbody, tr, th, td").forEach((elem) => {
  discardAttributes(elem, "cellspacing", "cellpadding", "width", "style");
});

My goal is now to encapsulate the above logic into a gulp.task like so:

const gulp = require("gulp");

gulp.task("clean", async () => {
 gulp.src("src/*.html")
  .pipe(discardAttributes())
    .pipe(gulp.dest("dist"));
});

If there exists a plug-in that can help achieve this task, please recommend, but I am also interested in learning how to do it manually as shown above.

Would utilizing 'through2' be necessary for this implementation?

Thank you.

Answer №1

If you're looking to manipulate the DOM using a node library, one approach is to incorporate gulp into the mix. A good combination to try is jsdom along with gulp-dom:

const gulp = require('gulp');
const dom = require("gulp-dom");

gulp.task("default", async () => {
 gulp.src("src/*.html")
  .pipe(dom(function() {

      // Custom function to remove multiple attributes from an element
      const discardAttributes = (element, ...attributes) =>
        attributes.forEach((attribute) => element.removeAttribute(attribute));

      // Apply the function to various elements
      return this.querySelectorAll("table, thead, tbody, tr, th, td").forEach((elem) => {
       discardAttributes(elem, "cellspacing", "cellpadding", "width", "style");
    });

  }))
  .pipe(gulp.dest("dist"));
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Trouble encountered while trying to display Angular in an HTML document

In my Angular project, there is a feature where a list of orders is displayed in one view. Each order is represented by its title only. When the user clicks on the title, they should be redirected to a new view showing the complete content of that particul ...

Using Vue.js to iterate over a list of items and accessing specific array objects by their unique identifier

My JSON array of objects has the following structure: https://i.sstatic.net/1IUVE.png When generating a <ul>, I need to fetch an ID from an API for each <li>: <ul> <li v-for="genre in movie.genre_ids"> {{ genre }} ...

Tips for increasing the number of inputs within a form using <script> elements

I am currently working on a form within the script tags and I would like to include additional input fields before submitting. However, the submit button seems to be malfunctioning and I suspect that there may be an issue with how I am accessing it in my c ...

What is the process for identifying children records of a parent (Adonis Lucid Many-to-Many) that match a specific criteria?

I am currently searching for the presence of specific Permissions within a single parent Role in a many-to-many relationship. const roles = await Role .query() .preload('permissions') this.role = roles.find(role => role.id === someid) co ...

Error: TypeScript Knockout table failing to display data

I have a table that displays invoices, along with a nested table showing the individual checks associated with each invoice. I am using knockout and typescript to render these tables. Currently, I can successfully display the invoices but am facing difficu ...

Is there a way to specify both a fixed width and a custom resizable length for a Spring <form:textarea /> element?

Despite extensive research, I have yet to find an answer to my specific problem. Within a model window, I have a textarea element: <div class="form-group"> <label for="groupDescription" class="col-sm-2 control-label"> Descripti ...

Tips for adding one document to two separate collections using JavaScript and MongoJS

Having trouble inserting data into two separate tables using javascript and mongojs. While I was able to successfully insert into a single collection by following the npm mongojs documentation, I couldn't find a solution for multiple collections on th ...

Angular Object Error: Unhandled Exception

As someone who is new to Angular, I am still trying to grasp how it functions. However, I have encountered an issue early on that is causing the below code to produce an "Uncaught Object" error in the console and disrupt Angular functionality. It seems t ...

Maintain the proportion of the browser window when reducing its size

<html> <head> <link rel="stylesheet" href="style.css" type="text/css" /> </head> <body> <img src="spacer--1200x800.png" width="1200" height="800" /> </body> </html> This section contains CSS ...

Building a Div Tag Layout with CSS for Full Width and Left Position of 300px

Experiencing some trouble with styling a div element. My goal is to have the div start at left:300px and stretch across the entire width of the browser window. However, when I apply width:100%, the div extends beyond the boundaries of the browser screen. ...

Installing npm modules can be a time-consuming task when running docker-compose

I have been working on a project using Next.js and a PostgreSQL database in a Docker container. The setup of my project involves Docker Compose. However, I've noticed that when I run docker-compose up, the npm install command takes an incredibly long ...

Troubleshooting custom filtering with jQuery Datatables across different tables is presenting challenges

I am currently utilizing the Datatables 1.10 jQuery plug-in and I am interested in implementing the custom search feature to filter two tables simultaneously on a single page, as shown below: function applyFilterByErrorClass(propertiesTable, errorClassNam ...

Certification could not be validated (grpc/node)

As I delve into this tutorial for guidance, my aim is to successfully execute the node example. After downloading the folder and navigating to the directory, I attempted running npm install. Here is the stack trace that was generated. npm WARN package.j ...

Tips for controlling the size of a canvas element: setting minimum and maximum width and height properties

function convertImageResolution(img) { var canvas = document.createElement("canvas"); if (img.width * img.height < 921600) { // Less than 480p canvas.width = 1920; canvas.height = 1080; } else if (img.width * img.he ...

The Controller received a JSON object that was empty

I know this question has been asked countless times, but I've tried all solutions with no success. Here's the JSON object in question: { "manufacture":"HP", "model":"testModel", "serialNumber":"testSerial", "description":"Test Descript ...

Changing the width of the file input using css

Clicking just below the word demonstration also triggers a click on the input type file. How can this be avoided so that the click event only fires in the intended area regardless of size? <!DOCTYPE html> <html> <body> <style> in ...

Switching back and forth between fluid text fields

Is there a way to navigate between dynamically generated textfields using an iterator from struts-tags? <s:iterator value="aList"> <td width="50px" align="center"> <s:textfield name="solField" size="2" maxlength="1" style="text-transform ...

Pass the ASP.NET MVC model onto the AngularJS scope

Here is the code snippet from my view with temporary JavaScript code for testing: I am trying to assign the ASP.NET MVC model (@Model) to the AngularJS scope ($scope.person). Any suggestions on how to accomplish this? Thank you, The View @model MyApp. ...

Having difficulty uploading an npm package to the GitLab registry

I am having trouble with a basic setup for publishing a node package to GitLab's package registry. I started a project using GitLab's Node Express template, but when I try to run npm publish, I encounter the following error: npm notice npm notic ...

The function Slice() does not function properly when used with two-dimensional arrays

I have been attempting to duplicate a 2D array by value using the slice() method in order to prevent any changes made to the new array from impacting the original. Oddly enough, it seems that this approach is effective with a 1-dimensional array but not wi ...