3

I want to select all elements that do not have the class "myclass". How can I do that in Cytoscape.js?

According to http://js.cytoscape.org/#selectors/data, "[^name] Matches elements if the specified data attribute is not defined", however a class is not a data attribute and ^.myclass does not work, neither does :not(.myclass).

The error is The selector :not(.myclass) is invalid.

Is there a way to negate classes?

Konrad Höffner
  • 11,100
  • 16
  • 60
  • 118

2 Answers2

2

If you want to get the negative class selector, you can do this:

cy.elements().not(cy.$('.yourClass'));

// in more detail
var allElements = cy.elements(); // get all elements
var negators = cy.$('.yourClass');  // get all elements with the class to negate
var result = allElements.not(negators); // gets the difference between the two collections
Stephan T.
  • 5,843
  • 3
  • 20
  • 42
  • 1
    I would prefer to have it inside the selector but if that it isn't possible I will use this, thanks! – Konrad Höffner Jan 09 '19 at 15:31
  • 2
    `eles.data('isFoo', true)` has the same relative performance as `eles.addClass('foo')`. If you're using a class for real state (not just visual styling), it probably makes more sense to use a data field. – maxkfranz Jan 11 '19 at 18:46
1

If you really want to achieve this by using selectors only, then you might add a data field to each element which has myclass (this can be done while adding the class), and then use [^myclass]

user3140972
  • 995
  • 6
  • 11
  • There seems to be no way to set an attribute to a set of elements and I don't want to loop through all of them because of the performance impact. – Konrad Höffner Jan 11 '19 at 10:06
  • 2
    `eles.data('isFoo', true)` should set the attribute for all elements. But it will also affect the performance in some ways. – user3140972 Jan 13 '19 at 22:33