title: this.setAttribute is not a function when using D3's .attr method
body: <p>I have a bar graph in D3 and I want to update the bars using a custom function update_bars(). Each rect element has been assigned an id from 0 to 9. The function is supposed to select the rect by id then change the width attribute, but I get "this.setAttribute" not a function. However, when I use plain old javascript, it works fine. I've commented where things went wrong. </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE&gt;
  &lt;html&gt;
  &lt;head&gt;
  &lt;link rel="shortcut icon" href=""&gt;
  &lt;script src="https://d3js.org/d3.v4.min.js"&gt;&lt;/script&gt;
  
  &lt;/head&gt;
  &lt;body&gt;
   
  &lt;script&gt;
  
  &lt;!-- everything works fine here --&gt;
  var width = 800, barHeight = 20, height = barHeight*10;
  var chart = d3.select("body")
   .append("svg")
   .attr("width", width)
   .attr("height", height); 
  var init_year = 2000;
  
  d3.json("topten.json", function(data){
   the_data = data;
   
   var bar = chart.selectAll("g")
      .data(data[init_year])
      .enter()
      .append("g")
      .attr("transform", function(d, i){
       return "translate(0," + i * barHeight + ")";
      })
  
      
    bar.append("rect")
     .attr("width", function(d){
      return d['articles']
     })
     .attr("height", barHeight - 1)
     .attr("id", function(d,i){ return i; } );
   
  });
  
  &lt;!-- problem is in update_bars() --&gt;
  
  function update_bars(data, yr){
   
   data[yr].forEach( function(d, i){
  
   &lt;!-- this d3 code gives "this.setAttribute is not a function" error --&gt;
   
   /. d3.select(i).attr("width", d['articles']); ./
   
   &lt;!-- this javascript works --&gt; 
   temp = document.getElementById(i); 
   temp.setAttribute("width", d['articles']);
   });
  }
  
  
  
  &lt;/script&gt;
  &lt;/body&gt;
  &lt;/html&gt;</code></pre>
  </div>
  </div>
  </p>