2016-12-02 93 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; 
     })); 
    });