I am needing a Gulp task that will go through all assigned HTML documents and remove certain attributes (such as style=""). I thought I may have been able to do it the same way I do it through the browser, but looks like not. Here is what I am trying to do:
// function to take multiple attributes from an element
const discardAttributes = (element, ...attributes) =>
attributes.forEach((attribute) => element.removeAttribute(attribute));
// run the function on multiple elements
document.querySelectorAll("table, thead, tbody, tr, th, td").forEach((elem) => {
discardAttributes(elem, "cellspacing", "cellpadding", "width", "style");
});
I would like to then take the above formula and create 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 is a plug-in I can use that will do this please share, but also, I'd like to learn how to do it manually like this.
Would I need to use through2?
Thank you.
CodePudding user response:
You can use some node dom library, and wrap it with gulp. For example you could try jsdom and wrapper gulp-dom:
const gulp = require('gulp');
const dom = require("gulp-dom");
gulp.task("default", async () => {
gulp.src("src/*.html")
.pipe(dom(function() {
// function to take multiple attributes from an element
const discardAttributes = (element, ...attributes) =>
attributes.forEach((attribute) => element.removeAttribute(attribute));
// run the function on multiple elements
return this.querySelectorAll("table, thead, tbody, tr, th, td").forEach((elem) => {
discardAttributes(elem, "cellspacing", "cellpadding", "width", "style");
});
}))
.pipe(gulp.dest("dist"));
});