How do I console.log an attribute in a dropdown menu?

Viewed 241

I am trying to console.log the 'data-id' attribute however I keep getting 1 in my console when I click on a new '.dropdown-item'. This is a snippet of the HTML:

<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
  {% for date in joined_dates %}
    <a class="dropdown-item" href="#" data-id="{{loop.index}}">{{date}}</a>
  {% endfor %}
</div>

This is a snippet of the javascript:

d3.json('/data', function(error, closure_data) {
  var btn = d3.selectAll('.dropdown-item')
  btn.forEach(function(value, index) {
    value = btn.attr('data-id')
    btn.on('click', function() {
      d3.select('#text').text('1')
      console.log(value)
    })
  })
})
1 Answers

Thanks to @altocumulus, I found a pretty simple solution and here it is:

d3.selectAll('.dropdown-item').on("click", function() { d3.select('#text').text('1'); console.log(this.dataset.id); })

Explanation to this I guess is that the data-id is a subset of data- classes and its value can be called upon by using .dataset.id. My understanding is we can put almost anything after data- when creating the class and still get the same result.

If anyone has a better explanation, please let me know! Thank you!

Related