Tips for deleting a CSS class from a Wicket element

If you're looking to dynamically update a CSS class of a component in Java code, one way to do so is by using an AttributeAppender:

component.add(new AttributeAppender("class", true, new Model<String>("foo"), " "));

You can also utilize a utility method or class like this:

component.add(WicketUtils.cssClassAppender("foo"));

However, removing a CSS class may not be as straightforward.

To remove all existing CSS classes, you can clear the class attribute entirely:

component.add(new SimpleAttributeModifier("class", ""));

But if you want to keep other CSS classes intact, this approach may not be suitable.

This solution is based on Wicket 1.4, but advice for later versions is welcome too.

Answer №1

Here is a possible solution that I devised:

public class CssClassRemover extends AttributeModifier {
    public CssClassRemover(String cssClass) {
        super("class", false, new Model<String>(cssClass));
    }

    @Override
    protected String newValue(String currentValue, String valueToRemove) {
        // Please note that this approach may not work in all scenarios, such as "foo foo-bar" & "foo"
        return currentValue.replaceAll(valueToRemove, "");
    }
}

To use the above helper code, you can do the following:

component.add(new CssClassRemover("foo"))

(Alternatively, you can create anonymous AttributeModifier subclasses based on your requirements, but utilizing a separate utility class or method can enhance readability.)

Edit: A revised version of newValue() which addresses potential issues more effectively (refer to biziclop's comment). Note: this implementation relies on Guava. (Feel free to suggest simpler alternatives like regex-based solutions.)

@Override
protected String newValue(String currentValue, String valueToRemove) {
    if (currentValue == null) return "";

    Set<String> classes = Sets.newHashSet(Splitter.on(" ").split(currentValue));
    classes.remove(valueToRemove);
    return Joiner.on(" ").join(classes); 
}

Answer №2

Expanding on Jonik's initial response, this code snippet incorporates negative lookahead to exclude instances within a different style class (and remains insensitive to case).

public class StyleClassRemover extends AttributeModifier {

    public StyleClassRemover(final String cssClass) {
        super("class", false, Model.of(cssClass));
    }

    @Override
    protected String newValue(final String currentValue, final String valueToRemove) {
        if (currentValue == null) {
            return "";
        }

        final String patternString = "(^|\\s+)" + Pattern.quote(valueToRemove) + "(?!\\S)";
        return Pattern.compile(patternString, Pattern.CASE_INSENSITIVE).matcher(currentValue).replaceAll("");
    }
}

Example input for testing:

Answer №3

The method org.apache.wicket.AttributeModifier#remove() is available in Wicket version 1.5 and above.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on effectively utilizing the generic class type parameter class

One interesting aspect of my work involves a genetic class parameter public static <T> T parse(String json, Class<T> clazz) { T result = null; result = mapper.readValue(json, clazz); return result; } Imagine there is a JSON object l ...

Center text within a span element

I'm struggling to set up arrow navigation with both next and previous buttons that need to function in Internet Explorer 7 and newer versions. For the next button, I want the background image to appear to the right of the text. As for the previous bu ...

Steer clear of posting additional content that might bump the existing content further up

How can I keep the search bar centered on the screen, even when content is added below it? Here's a screenshot illustrating the issue: https://i.stack.imgur.com/7pQ1q.png The text in the image is causing the search bar to move up, but I want the sea ...

Develop a circular carousel using React JS from scratch, without relying on any third-party library

I am looking to replicate the carousel feature seen on this website. I want to mimic the same functionality without relying on any external libraries. I have found several resources explaining how to achieve this. Most suggest creating duplicate copies o ...

Integrating a Find Pano functionality into a Kolor Panotour

I used a program called Kolor to create a panorama. Now, I am attempting to integrate the "find pano" feature, which involves searching through the panoramic images for display purposes. I have come across an HTML file that contains the search functionalit ...

CSS transform causing scrolling issues in Microsoft Edge browser

Whenever I click a button, a div flips. Once flipped, the div contains a scrolling list. If the list is not long enough to scroll, everything works fine. However, if the list is long enough to require scrolling, the items disappear... This issue ...

I am looking to adjust the height of my MUI Grid component

Recently exploring React, and I'm looking to set a height limit for MUI Grid. I've structured my project into 3 sections using MUI grid components. My goal is to restrict the page height in order to eliminate the browser scrollbar. If the conten ...

Java Arrays and Output: A Comprehensive Guide

I'm currently working on a program that automates the creation of an Operations Order (OPORD). It's not too complex, but I'm encountering some difficulties with my arrays, particularly in getting them to display properly in the output. Here& ...

Content does not become interactive upon the initial loading of the page

I've modified a W3 schools slideshow template to use text instead of dots, but I'm encountering two issues 1: The first image doesn't load when the page loads. Although using a class ID and setting it to active fixes this issue, it leads to ...

Styling Angular Datatables with CSS

i have data on the front end https://i.stack.imgur.com/2xq7a.jpg i need all check marks to be displayed in green color. Below is the code snippet: $scope.dtColumnsCal= [ DTColumnBuilder.newColumn('name').withTitle('Name') ...

Using CSS3, you can apply multiple backgrounds to an unordered list with one set

Currently, I am in the process of working on a unique Wordpress template. One of the challenges I am facing is figuring out how to incorporate three background images for each <li> element in the dynamically generated navigation menu. Here are two ex ...

Select a color by inputting the type as "color" while leaving a space between the border and

I'm having an issue with the color input There seems to be a gap between the black border and the actual color, but I want to get rid of it #color-picker { border: 5px solid black; border-radius: 5px; width: 207px; height: 60px; padding: ...

HTML5, canvas covering every element

Below is the code that I am working with: <html> <head> <title>canvas</title> </head> <body> <canvas width="1745" height="569" style="width: 1730px; height: 1680px; position: absolute; z-index: 1"></canvas> ...

Issue: The drawOval method in the Graphics class is not applicable to the given types. Unclear as to the reason behind this error message

An error is happening specifically on the line where g.drawOval is being called. public void paint(Graphics g) { g.drawLine(150, 500, 150, 200); g.drawLine(01, 200, 644, 200); g.drawLine(430,200,430,500); g.drawLine(300,200,300,002) ...

Navigation bar with dropdown functionality that adjusts its width based on the content inside

Need help with a CSS dropdown menu issue on my WordPress site. The contents of the submenus are too wide, even after setting a static width for them. I'm looking for a way to make the submenu width adjust dynamically based on the title length. Any exp ...

Is it possible to personalize CSS properties using PHP sessions?

Currently, I am a beginner in PHP and enrolled in a technical school class to learn more about it. Our latest assignment involves using sessions to modify four CSS properties: body background-color, a:link color, a:hover color, and h1 color. The task inclu ...

Retrieve all incoming emails from a Microsoft Exchange account using Java

Currently, my program is configured to display all emails from my Gmail account. However, I would like it to show incoming emails from a Microsoft Exchange account instead. Can someone advise me on which properties need to be modified for this change? ` ...

Transform the snake code by incorporating a visual image as the face of the serpent

Can someone help me change the snake's face to an image instead of a color fill in this code? And how can I add arrows for mobile compatibility? (function() { // Insert JS code here })(); // Insert CSS code here This code snippet includes functi ...

Improving the way text entered in an input box is displayed using HTML table cells

Seeking advice on how to display the last two input boxes in a dynamic HTML table so that users can easily view the data they have entered. The issue arises when the length of the data in these columns is large, making it difficult for users to see all the ...

Is there a way to remove the ring shadow in TailwindCSS?

Here is a visual representation of the issue I'm facing (refer to the image): Check out the Image After inspecting with Chrome, it seems like the problem is connected to --tw-ring-shadow. I attempted to use classes like ring-0 and ring-offset-0 (men ...