Accepted answer

My question is why the d3 selectAll statement (above the createNode function) does not work when I run the script after page load, though it all runs fine when I cut and paste that same statement into the browser console.

Currently you append a factory node that creates new nodes on click.

Then you select all existing circles with class node. At this point there are none.

Then you can click on the factory node, create a new one, but you don't re-run the selectAll statement. The selection of all circles is not updated because a new circle is created afterwards.

What you could do is run the selectAll statement again after you append a node, but you only add one node at a time, and you already have a selection of that node in the createNode function. So you can just add the event listener here:

 function createNode(x,y) { 
    var r=30; var lx=random(100+r,w-r); var ly=random(0+r,h-r); 
    var rx=svg.append('circle')


    var w=500,h=400,ctr=0; //define bounds of svg

        var ND=[]; //holder of all node data

    var svg ='body').append('svg') //base svg element

    function random(p,q) { return p+Math.floor(Math.random()*(q-p)); }

    var factory=svg.append('circle') //draw the factory widget
        .attr('class','perms') //one of the perm objects

    factory.on('click',createNode); //create a new node when factory is clicked

    function createNode(x,y) //create a new node and render on screen
    { var r=30; var lx=random(100+r,w-r); var ly=random(0+r,h-r); 
      var rx=svg.append('circle').attr('class','nodes').attr('id',ctr)
        .on('click',function(e,d){ var; console.log(did); 
      var rn={id:ctr++, x:lx, y:ly, r:30, clr:'yellow',lnk:[],ptr:0};
      return rn;
<script src=""></script>

The selectAll code works in the console after you add circles because now there are circles to select - otherwise you have an empty selection. One way you can check to see if you are indeed selecting anything is to use selection.size() to return how many elements are selected.

Related Query

More Query from same tag