Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select nodes by class in cytoscape.js?

CYTOSCAPE.JS

I can't manage to apply styles to a class defined in node-data (clLevel0). I wrote a function to work around the problem. So, the function also explains what i want to do, in a much simpler way that is ;-)

function setNodesClassStyles(cy, clas, styleobject)
 {
   var all = cy.nodes();
   for (i = 0; i < all.length; i++) {
       the_node = all[i];
       all_classes = the_node.data().classes;
       //alert(all_classes);
       if (all_classes != undefined) {
           all_classes = all_classes.split(' ');
           for (i = 0; i < all_classes.length; i++) {
               alert(all_classes[i]);
               if (clas == all_classes[i]) {
                   the_node.style(styleobject)
               }

           }
       }
   }
 };
setNodesClassStyles(cy, "clLevel0", {'background-color':'#00E'});

I tried this (not working):

{
  selector: ".clLevel0",
  style: {
    'background-color': '#EAA',
  }
},

What's the right way to apply styles on a node with a class 'clas'? More code:

    var cy = cytoscape({

      container: document.getElementById('cy'), // container to render in

      elements: [ // list of graph elements to start with
      // LEVEL 0 NODE
        { // node 
          data: { id: 'me', name: 'Dirk\n@dickschrauwen', classes: 'clLevel0 clRoot', weight: 10000},

          "position": {
           "x": 600,
           "y": 400 },

        },

     // LEVEL 1 NODES
        {
          data: { id: 'skills', name: 'Skills',  }
        },  
        {
          data: { id: 'education', name: 'School' }
        },
        {
          data: { id: 'work', name: 'Jobs\nProjects' }
        },
        { 
          data: { id: 'passion', name: 'Passions' }
        },

// ....
  style: [
    {
      selector: 'node',
      style: {
        'height': 40,
        'width':  40,
        //'height': 20,
        //'width':  20,
        'background-color': '#EE0',
// ....

    {
      selector: ".clLevel0",
      style: {
        'background-color': '#EAA',
      }
    },

  ],
//...
like image 536
Dick Schrauwen Avatar asked Sep 05 '25 18:09

Dick Schrauwen


1 Answers

document.addEventListener("DOMContentLoaded", function() {

  var cy = cytoscape({
    container: document.getElementById('cy'),
    elements: {
       nodes: [
          { data: { id: 'n', label: 'Olo' } },
          { data: { id: 'c'}, classes: 'className'}
    ]}
   });
  cy.style.fromJson([
      {
         selector: 'node',
         style: {
             'color': 'red'
         }
       },{
         selector: '.className',
         style: {
             'label': 'this has a class',
             'color': 'blue'
        }
      }
   ])
}); 
like image 156
Tom Aerts Avatar answered Sep 08 '25 07:09

Tom Aerts