简体   繁体   中英

How to select elements in a forEach loop? D3

I am trying to modify an attribute in my links for a passed in Node object.

I am getting this error:

this.setAttribute is not a function

I am wondering what the restrictions are on the select operator. This is my current implementation:

function setChildrenLinkWidth(node) {
    node.links().forEach(function (i) {
        d3.select(i.source)
        .attr("stroke", "blue");
     });
 }

If anyone knows, I would appreciate it.

For reference, I have tried

d3.select("#" + i.source)

And I get the error:

Failed to execute 'querySelector' on 'Document': '#[object Object]' is not a valid selector.

Edit:

Here is some more code:

    // Creating nodes here
    let nodeEnter = node.enter().append('g')
    .attr('class', 'node')
    .attr("transform", function (d) {
        return "translate(" + source.x0 + "," + source.y0 + ")";
    })
    .on('click', click);
nodeEnter.append('circle')
.attr('class', 'node')

 // Functions

function setChildrenLinkWidth(node) {
node.links().forEach(function (i) {
    console.log(i.source);
    d3.select(i.source.id)
    attr("stroke", "blue");
 });
}

function click(d) {
    if (d.children) {
        d._children = d.children;
        d.children = null;
    } else {
        d.children = d._children;
        d._children = null;
    }
    update(d);
    setChildrenLinkWidth(d);
}

I think it is because that i.source is the node that is the source and not simply the string you likely think you're getting based on the data... Therefore if you do d3.select("#" + i.source.id); it will select the element with that ID. Unless your i.source for each links is an object.

I can clarify more if you post your data structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM