I am using owasp-java-html-sanitizer and try to add id-attributes to each h2-tag in my HTML Code, which should be persistent over several page loads but unique for each element on the page(as defined for id-attributes). I tried to count all elements to get an index and to add the index to every h2 element. However, I have no access to this data at this point in java. Then I used UUID.randomUUID(), however as it is random, the id is not persistent.
Here is the code I have currently:
public PolicyFactory HtmlPolicy() {
return new HtmlPolicyBuilder()
.allowElements("h3", "h4", "h5", "h6", "p", "span", "br", "b", "strong", "i", "em", "u", "hr", "ol", "ul", "li",
"img", "table", "tr", "th", "td", "thead", "tbody", "tfoot", "caption", "colgroup", "col", "blockquote", "figure", "figcaption", "object", "iframe")
.allowElements(
(String elementName, List<String> attrs) -> {
String uniqueID = UUID.randomUUID().toString();
// Add an attribute.
attrs.add("id");
attrs.add("headline-" + uniqueID);
attrs.add("class");
attrs.add("scrollspy");
// Return elementName to include, null to drop.
return elementName;
}, "h2")
.toFactory();
}
In javascript I would do it as follows:
$('h2').each(function(index, obj) {
let newObj = $(obj)[0];
$(newObj).attr('id', `headline-2-${index + 1}`);
});
Does anyone have an idea of an approach to increment one on every h2-element in this szenario?