Search code examples
javascriptd3.jsreferencenaming

d3 javascript naming or referring to groups


I am trying to reference different groups in d3 in order to change colours of the contents inside each of the groups for the function onHover. For example I have two groups both consisting of rectangles. I want to select one group and make them all one colour and I want to select the other group and make them a different colour.

Is there a way to reference each group and perform specific demands?

such that:

    var group1 = canvas.append("group1: g"); //contains rects
    var group2 = canvas.append("group2: g"); //contains rects


    d3.select("group1").style() //change colour

Solution

  • You can give IDs or classes to the g elements and select accordingly:

    canvas.append("g").attr("id", "foo");
    canvas.append("g").attr("class", "bar");
    
    canvas.selectAll("g#foo");
    canvas.selectAll("g.bar");