[D3.js] Error when selecting DOM element using `this`

Hi, I’m currently doing the bar chart for data vis project. Attempting to select the svg <rect> element using this from within on('mouseover', function() {}) results in an error message.

Below is my current code:

svg.selectAll('rect')
  .data(dataset.data)
  .enter()
  .append('rect')
  .attr('x', (d) => xScale(new Date(d[0])))
  .attr('y', (d) => yScale(d[1]))
  .attr('width', (d) => (w - 2*padding)/len)
  .attr('height', (d) => h - padding - yScale(d[1]))
  .attr('class', 'bar')
  .attr('data-date', (d) => d[0])
  .attr('data-gdp', (d) => d[1])
  .attr('index', (d, i) => i)
  .on('mouseover', (event, d) => {
  
    let i = this.getAttribute('index');
    let dataDate = this.getAttribute('data-date');
    let dataGDP = this.getAttribute('data-gdp');
  
    d3.select(this)
      .transition()
      .duration('50')
      .attr('opacity', '0.85');

    tooltip.transition()
           .duration('50')
           .attr('opacity', '1');

    tooltip.html(
      dataDate + '<br>' + dataGDP
    );

Error message:

Uncaught TypeError: this.getAttribute is not a function
    at SVGRectElement.<anonymous>

Full codes on codepen if necessary: https://codepen.io/prieton/pen/wvmpVRb

You are trying to use this inside an arrow function. Arrow functions do not have their own bindings to this.

1 Like

I see. Thanks for the help!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.