Search code examples
for-loopvis.jsvis.js-network

(Vis.js network) How do I put the nodes array in a loop to get my data?


I have several div containing data that I want to use as id, label, title etc for the nodes of my network.

I made a for loop which gets all the existing div with a specific class, and then stores the contents of all the child div in variables. In order to generate as many nodes as there are div, I assume the next step is to put the nodes array inside the loop, but if I do that the network doesn't load.

Here's the code that I have right now: it generates only one node, containing the data of the last div, since the nodes array is out of the loop. How do I correctly put it in the loop?

    var nombreNodes= $('.personnage');
    for (var i = 0; i < nombreNodes.length; i++) {
        var nodesId = document.getElementsByClassName('id')[i].innerHTML;
        var nodesLabel = document.getElementsByClassName('label')[i].innerHTML;
        var nodesTitle = document.getElementsByClassName('title')[i].innerHTML;
        var nodesGroup = document.getElementsByClassName('group')[i].innerHTML;
        var nodesFontSize = document.getElementsByClassName('fontSize')[i].innerHTML;
        var nodesFontColor = document.getElementsByClassName('fontColor')[i].innerHTML;
        var nodesFontFace = document.getElementsByClassName('fontFace')[i].innerHTML;
    }

    // create an array with nodes
    var nodes = [
        {id: nodesId, 
        label: nodesLabel, 
        title: nodesTitle, 
        group: nodesGroup, 
        font: nodesFontSize + ' ' + nodesFontFace + ' ' + nodesFontColor},
    ];

Solution

  • As I think, you need to add the nodes to an array, which will be available from outside of the for-loop. The following example should work (currently untested)

    var nodes = [];
    var nombreNodes= $('.personnage');
    for (var i = 0; i < nombreNodes.length; i++) {
        var nodesId = document.getElementsByClassName('id')[i].innerHTML;
        var nodesLabel = document.getElementsByClassName('label')[i].innerHTML;
        var nodesTitle = document.getElementsByClassName('title')[i].innerHTML;
        var nodesGroup = document.getElementsByClassName('group')[i].innerHTML;
        var nodesFontSize = document.getElementsByClassName('fontSize')[i].innerHTML;
        var nodesFontColor = document.getElementsByClassName('fontColor')[i].innerHTML;
        var nodesFontFace = document.getElementsByClassName('fontFace')[i].innerHTML;
    
        nodes.push({
            id: nodesId, 
            label: nodesLabel, 
            title: nodesTitle, 
            group: nodesGroup, 
            font: nodesFontSize + ' ' + nodesFontFace + ' ' + nodesFontColor
        });
    }
    // This dataset can be added to the vis.network
    var dataSet = new vis.DataSet(nodes);