Customize
Custom pseudo classes and functions

Custom pseudo-class

Custom pseudo-classes extends the PseudoClass and implements match(Node node). This method should return true if a node is matched. You may also override the method getPseudoClassName() if you don't want to generate a pseudo-class name from the class name. For example:
1
public class MyPseudoClass extends PseudoClass {
2
@Override
3
public boolean match(Node node) {
4
return node.hasAttribute("jodd-attr");
5
}
6
​
7
@Override
8
public String getPseudoClassName() {
9
return "jodd";
10
}
11
}
Copied!
Then register your pseudo-class with:
1
PseudoClassSelector.registerPseudoClass(MyPseudoClass.class);
Copied!
From that moment you will be able to find all nodes with the attribute jodd-attr using the :jodd pseudo-class.
When a pseudo-class needs to perform an additional match in the range of matched nodes (e.g. first, last etc), then override matchInRange() method, too.

Custom pseudo-function

Similar to pseudo-classes, custom pseudo-function implements the PseudoFunction class. Additionally, you need to also implement a method that parses input expression. This expression is later passed to the matching method.
Let's make a function that matches all nodes with certain name length:
1
public class MyPseudoFunction extends PseudoFunction {
2
@Override
3
public Object parseExpression(String expression) {
4
return Integer.valueOf(expression);
5
}
6
​
7
@Override
8
public boolean match(Node node, Object expression) {
9
Integer size = (Integer) expression;
10
return node.getNodeName().length() == size.intValue();
11
}
12
​
13
@Override
14
public String getPseudoFunctionName() {
15
return "len-fn";
16
}
17
}
Copied!
Register it with:
1
PseudoFunctionSelector.registerPseudoFunction(MyPseudoFunction.class);
Copied!
Start using it! E.g. :len-fn(3) to match all nodes with short names:)
Last modified 1yr ago
Export as PDF
Copy link