score:8

Accepted answer

If you want access to the element, it's implicit in D3's iterators via this.

d3.selectAll('.node').each(function(d) {
  console.log(this); // Logs the element attached to d.
});

If you really need access to the id, you can get it with selection.attr():

d3.selectAll('.node').each(function() {
  console.log(d3.select(this).attr('id')); // Logs the id attribute.
});

You don't have to use each. Any of the iterators, such as attr or style, etc., have 'this' as the bound element:

d3.selectAll('.node').style('opacity', function(d) {
  console.log(this);// Logs the element attached to d.
});

If you want the x and y coordinates of a node, it's part of the data:

d3.selectAll('.node').each(function(d) {
  console.log(d.x, d.y); // Logs the x and y position of the datum.
});

If you really need the node attributes themselves, you can use the attr accessor.

d3.selectAll('.node').each(function(d) {
  // Logs the cx and cy attributes of a node.
  console.log(d3.select(this).attr('cx'), d3.select(this).attr('cy'));
});

EDIT: It looks like you need an element reference, but the only thing you know about the node in context is its position. One solution is to search through all nodes for a node with matching coordinates.

// Brute force search of all nodes.
function search(root, x, y) {
  var found;
  function recurse(node) {
    if (node.x === x && node.y === y)
      found = node;
    !found && node.children && node.children.forEach(function(child) {
      recurse(child);
    });
  }
  recurse(root);
  return found;
}

However this only gives you the node object, not the element itself. You will likely need to store the element references on the nodes:

// Give each node a reference to its dom element.
d3.selectAll('.node').each(function(d) {
  d.element = this;
});

With that in place, you should be able to access the element and get its id.

var id, node = search(root, x, y);
if (node) {
  id = node.element.getAttribute('id');
}

The brute-force search is fine for a small number of nodes, but if you're pushing a large number of nodes you might want to use D3's quadtree (example) to speed up the search.

score:1

Use d3.select('#yourElementId')

For more info check this out: https://github.com/mbostock/d3/wiki/Selections


Related Query

More Query from same tag