Search code examples
javascriptd3.jsvuejs2getattribute

vuejs + d3: select returns element, but attr() returns null


I'm confused a bit, please help me to figure out a problem.

I am using VueJS + d3.js.

I have a code that looks like this:

<template>
  <div class='chart-frame-chart-comp border-black-1 border-radius-1'>
    <div class='plot'>
    </div>
  </div>
</template>

<script>
import * as d3 from 'd3'

export default {
  name: 'chart-frame-chart-comp',

  mounted () {
    this.$nextTick(this.plot)
  },

  methods: {
    plot () {
      console.log(this.getPlotSize())
    },

    getPlotSize () {
      let a = d3.select('.chart-frame-chart-comp .plot')
      console.log('a', a)
      let b = a.attr('tagName')
      console.log('b', b)
      return b
    }
  }
}
</script>

In getPlotSize I am trying to return an attribute of a selected element (the one with .plot class)

So in debugger, I see output:

enter image description here

Obviously, d3 managed to obtain a node (since it is the actual element, I was looking for plus selection return only one element that, again, I was looking for). But when d3 tries to return value of getAttribute, former returns null and hasAttribute returns false. But Chrome debugger sees that element has those attributes:

enter image description here

Obviously I'm missing something! So my question is: what am I doing wrong?


Solution

  • This is a misconception as there is no attribute tagName on your node. What you see in your console is the tagName property of the Element you selected. At the time you are selecting the element—as shown in your second screenshot— there are two attributes, namely class and data-v-391ae376. Hence, neither .getAttribute("tagName") nor D3's .attr("tagName") will return any value.

    If you are interested in the element's tagName you can simply call selection.node() to get the first element in the selection and access its tagName property afterwards. In your example this will print "div".

    getPlotSize () {
      let a = d3.select('.chart-frame-chart-comp .plot');
      console.log('a', a);
      let b = a.node().tagName;   // Get the DOM node and read its tagName property
      console.log('b', b);
      return b;
    }