【发布时间】:2016-12-02 05:32:44
【问题描述】:
我在编写一个 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 元素。非常感谢任何形式的帮助。
【问题讨论】:
标签: javascript jquery html gulp