2016-12-02 48 views
0

我在编写基本上将小型HTML代码添加到应用程序中所有现有html文件中的gulp任务时遇到问题。 所以我现有的HTML看起来像gulp任务预先将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文件中添加一个更多的跨度元素,使其位于错误消息的正上方。这样的事情:

<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-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; 
    })); 
}); 

我知道我在循环里面弄得一团糟。它正在工作,但并不像预期的那样。它应该去每个文件夹和每个文件,并寻找小的元素,然后预先跨度元素。任何形式的帮助真的很感激。

回答

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; 
     })); 
    });