我在编写gulp任务时面临一个问题,该任务基本上将小HTML代码预先添加到应用程序中的所有现有html文件中。 所以我现有的HTML看起来像
<div class="input-field-group">
<span class="error-validation">
<small class="inline-error">
<span>This field is required</span>
</small>
<small class="inline-error">
<span>This field is required</span>
</small>
<small class="inline-error">
<span>This field is required</span>
</small>
</span>
</div>
这在整个应用程序中的多个html文件中是相同的。我想要添加的是在整个应用程序的所有html文件中的错误消息之上的另一个span元素。像这样的东西:
<div class="input-field-group">
<span class="error-validation">
<small class="inline-error">
***<span aria-hidden="true" class="error-icon"></span>***
<span>This field is required</span>
</small>
<small class="inline-error">
***<span aria-hidden="true" class="error-icon"></span>***
<span>This field is required</span>
</small>
<small class="inline-error">
***<span aria-hidden="true" class="error-icon"></span>***
<span>This field is required</span>
</small>
</span>
</div>
我已经开始写下gulp任务了,但是介于两者之间。我正在使用gulp-dom插件。
var gulp = require('gulp');
var dom = require('gulp-dom');
gulp.task('prepend-html', function(){
return gulp.src('./**/*.html')
.pipe(dom(function(){
var divLengths = this.querySelectorAll('small').length;
var parentDiv = this.querySelector('small');
for(var i = 0; i < divLengths; i++) {
var childSpan = this.createElement('span');
childSpan.setAttribute('aria-hidden', 'true');
childSpan.setAttribute('class', 'error-icon');
parentDiv.insertBefore(childSpan, parentDiv.firstChild);
return this;
}
}))
.pipe(gulp.dest(function(file){
return file.base;
}));
});
我知道我在循环中弄得一团糟。它工作但不如预期。它应该转到每个文件夹和每个文件并查找小元素,然后添加span元素。任何形式的帮助都非常感谢。
答案 0 :(得分:0)
您只在for循环中对单跨执行操作。以下将有效 -
var gulp = require('gulp');
var dom = require('gulp-dom');
gulp.task('default', function(){
return gulp.src('./**/*.html')
.pipe(dom(function(){
var divLengths = this.querySelectorAll('small').length;
var parentDiv = this.querySelectorAll('small');
for(var i = 0; i < divLengths; i++) {
console.log(i);
var childSpan = this.createElement('span');
childSpan.setAttribute('aria-hidden', 'true');
childSpan.setAttribute('class', 'error-icon');
parentDiv[i].insertBefore(childSpan, parentDiv[i].firstChild);
}
return this;
}))
.pipe(gulp.dest(function(file){
return file.base;
}));
});