title: Inject repetitive code into functions: JavaScript
body: <p>The <code>add8</code> function below has a lot of <code>for</code> loops inside. I've truncated it for the purposes of this question but there's a good bit more loops in my original function from my source code. Have a look:</p>
  
  <pre><code>function select( selector ){
    return document.querySelectorAll( selector );
  }
  
  function add8(){
    var x = select( '[ x ]' ), y = select( '[ y ]' ),
      x1 = select( '[ x1 ]' ), y1 = select( '[ y1 ]' ),
      x2 = select( '[ x2 ]' ), y2 = select( '[ y2 ]' ),
      cx = select( '[ cx ]' ), cy = select( '[ cy ]' ),
      i = 0,
      val = 0;
  
    for( i = 0; i &lt; x.length; i++ ){
      val = x[ i ].getAttribute( 'x' );
      val = Number( val ) + 8;
      x[ i ].setAttribute( 'x', val );
    }  
    for( i = 0; i &lt; y.length; i++ ){
      val = y[ i ].getAttribute( 'y' );
      val = Number( val ) + 8;
      y[ i ].setAttribute( 'y', val );
    }    
    for( i = 0; i &lt; x1.length; i++ ){
      val = x1[ i ].getAttribute( 'x1' );
      val = Number( val ) + 8;
      x1[ i ].setAttribute( 'x1', val );
    }    
    for( i = 0; i &lt; y1.length; i++ ){
      val = y1[ i ].getAttribute( 'y1' );
      val = Number( val ) + 8;
      y1[ i ].setAttribute( 'y1', val );
    }
    // Alot more 'for' loops follow...
  }
  
  add8();
  </code></pre>
  
  <p>You might notice that there's only a few values needing to change in these for loops, So I'm desperate for a function that can reuse a lot of the code while making the overall code a lot shorter and concise.</p>
  
  <p>something like</p>
  
  <pre><code>function dynamicFunc( dynamicVar, dynamicStr ) {
    for( i = 0; i &lt; dynamicVar.length; i++ ){
      val = dynamicVar[ i ].getAttribute( dynamicStr );
      val = Number( val ) + 8;
      dynamicVar[ i ].setAttribute( dynamicStr, val );
    } 
  }
  
  function add8(){
    var x = select( '[ x ]' ), y = select( '[ y ]' ),
      x1 = select( '[ x1 ]' ), y1 = select( '[ y1 ]' ),
      x2 = select( '[ x2 ]' ), y2 = select( '[ y2 ]' ),
      cx = select( '[ cx ]' ), cy = select( '[ cy ]' ),
      i = 0,
      val = 0;
  
    dynamicFunc( x, 'x' );
    dynamicFunc( y, 'y' );
    dynamicFunc( x1, 'x1' );
    dynamicFunc( y1, 'y1' );
  
    // Alot more follow...
  }
  
  add8();
  </code></pre>
  
  <p>to automate those <code>for</code> loops, but the below example does not seem to work. I'm not too great at JS yet and think I need a little help here. How can I do this? Thank you.</p>
  
  <p><em>Note: I'm dealing with a lot of SVG's in my source-code, hence the attributes <code>x</code>, <code>y</code>, <code>x1</code> etc... being selected in my JavaScript.</em></p>
  
  <p><strong>Extra Note: I'm using vanilla JS here.</strong></p>