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.
<!DOCTYPE>
<html>
<head>
<link rel="shortcut icon" href="">
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>
<!-- everything works fine here -->
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; } );
});
<!-- problem is in update_bars() -->
function update_bars(data, yr){
data[yr].forEach( function(d, i){
<!-- this d3 code gives "this.setAttribute is not a function" error -->
/. d3.select(i).attr("width", d['articles']); ./
<!-- this javascript works -->
temp = document.getElementById(i);
temp.setAttribute("width", d['articles']);
});
}
</script>
</body>
</html>