1

All:

I wonder how do I select a DIV element with id="1" in D3, I can do it in jQuery, but when I turn to D3, it gives error like:

Uncaught DOMException: Failed to execute 'querySelector' on 'Document': 'div.chart#1' is not a valid selector

<div id="1"></div>

Thanks

Kuan
  • 11,149
  • 23
  • 93
  • 201

3 Answers3

8

The id TAG must start with letter, but you can use this:

d3.select('[id="1"]').append("div");

This is the example in JSFiddle

And here the technical explanation.

Baro
  • 5,300
  • 2
  • 17
  • 39
0

I had a situation when trying to select an element by id using d3 failed with the error:

Uncaught DOMException: Document.querySelector: 'obj_id' is not a valid selector.

My work around was to define a function

const d3Select = (id) => d3.select(document.getElementById(id))

an example of usage:

const dom = d3Select('obj_id')
   .attr('class','warning')

and it works just fine

milevyo
  • 2,165
  • 1
  • 13
  • 18
-1

If you gave it an ID, you can select it directly by ID. You don't need to specify div in the selector.

d3.select('#1')
.foo()
  • doesn't work for me either. I can select first object by type (in my case 'select') but not by id. EDIT: it works when I prefix the id with # – James Apr 08 '18 at 06:09