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

Is there a way to seamlessly inject a stylesheet into a React application without causing any flickering or reloading on the website?

In my React application built with next.js, I am fetching a stylesheet via a GET request and appending it to the webpage. However, whenever this stylesheet is loaded in, the elements impacted by it re-render unnecessarily, even if there are no actual chang ...

Utilizing CSS to Create Fixed Position Elements

How can I create a CSS Style with a fixed position property for a div? When I place this particular div inside another div containing text, the fixed-positioned div overlaps the text, causing it to be hidden. I want to align the text and image divs next ...

What is the method with the greatest specificity for applying styles: CSS or JS?

When writing code like the example below: document.querySelector('input[type=text]').addEventListener('focus', function() { document.querySelector('#deletebutton').style.display = 'none' }) input[type=text]:focu ...

Ensure that the elements are properly arranged inside divs that have been stretched

My goal is to create divs that are all the same size, while aligning some content within each div differently due to varying lengths. The objective is to keep the icon and text in a consistent position within all divs, but allow the divs to expand at the ...

Update the content of the widget

Currently, I am utilizing the following script to display NBA standings: <script type="text/javascript" src="https://widgets.sports-reference.com/wg.fcgi?script=bbr_standings&amp;params=bbr_standings_conf:E,bbr_standings_css:1&amp"></sc ...

CSS3PIE is failing to function properly in Internet Explorer

Looking for a solution to achieve rounded corners in Internet Explorer? Consider using . In my CSS file named template.css, I have included the following code which is loaded when the page loads on Joomla 1.5. .form_field {color:#222 !important; border:2p ...

After obtaining two IDs, I am required to add the first ID to the URL and click on the accept button. However, I am facing difficulties in adding the second ID to the URL afterwards

I am facing an issue with appending the second id to the URL after clicking on the accept button. The first id appends successfully, but the second one does not. Here is my current code: String confirmationURL = "https://test-website/#/email?type=proposa ...

Unable to handle a POST request initiated by an HTML Form

Recently, I started working with Express and Bootstrap. While attempting to create a login form that triggers a POST request to the server, I encountered an issue where the page displays "The page isn't working" instead of loading a new HTML page. He ...

The window.addEventListener function is failing to work properly on mobile devices

Hey there! I am facing an issue in my JS code. I wrote this code because I want the menu to close when a visitor clicks on another div (not the menu) if it is open. The code seems to be working fine in developer tools on Chrome or Firefox, but it's no ...

Performing Get() and Set() operations across multiple @Test annotations in Selenium WebDriver

I rely on Selenium WebDriver and Arquillian drone for my testing needs. Here is an example of my test setup : @RunWith(Arquillian.class) public class SimpleTest{ private String idPo; public String getIdPo() { return idPo; } public void set ...

Issue arises when applying both overflow-x:scroll and justify-content:center

Encountering a problem with using overflow-x: scroll and justify-content: center on a flex parent container. Here is my code snippet: The issue: the first flex child item is not visible as it is cropped on the left side. Please refer to the screenshot and ...

Ensure that the heading cells in the table header (thead) are properly

Struggling with aligning the thead with the td in the tbody? I attempted adjusting the thead using display: table-header-group;, but discovered that padding doesn't work on 'table-header-group'. This led me to try adding padding-left to my t ...

CSS Grid having trouble with wrapping elements

Greetings to all, As a newcomer to the world of web development, I am currently exploring the wonders of the CSS grid tool. However, I have encountered a roadblock: My intention is for the cards to automatically flow one by one into the next row while ma ...

What methods can be employed to maintain a consistent width for a multi-line span that aligns with the content?

Inside a div, I have 2 spans. When the content of the first span is short enough to fit on one line, the span's width matches the text content and positions the second span next to it. If the content of the first span is long and causes it to wrap, t ...

Converting HTML divs into a single page PDF document using DinkToPdf

Having trouble generating PDF from HTML using DinkToPdf due to div elements splitting across pages? Is there a way to ensure the entire div stays on one page, perhaps through html/css? Ideally, if there is sufficient space, the div should remain on the c ...

Beginning multiple-threaded stopwatch instances (the commandHolder became filled while executing the doCommandWithoutWaitingForAReponse exception)

I am facing a challenge with a relatively simple concept... Our Dashboard loads multiple portlets, and I need to track the load time for each one. To achieve this, I have created a basic StopWatch class that needs to run concurrently for each portlet while ...

Transform text with spaces into a JSON object

I am facing an issue with the text I receive as a server response. My goal is to save it in shared preferences, but I encounter an exception due to white spaces and some keys with empty values. Name=Ali K,picture=, String jsonStr="{IsEmailSubscriptio ...

Is it feasible to generate a fixed lighting effect overlay with HTML and CSS?

Is it possible to incorporate a static lighting effect overlay using HTML/CSS? My project consists of an HTML5/JS app with a top navigation bar and a series of cards that are transitioned through using swipe gestures. These cards are displayed in gray ove ...

Navigating through Expression Engine and utilizing conditional statements

Would greatly appreciate some assistance with this issue. I am working on an Expression Engine website and encountering difficulties with simple conditionals for navigation active states. Despite having a color state designated within the styles, there s ...

Allow the content to be scrolled

When it comes to my CSS script, I encounter no issues on larger computer screens. However, users with smaller resolutions like 1024 x 768 are experiencing problems viewing the entire HTML page. Only half of the page is displayed, making it impossible for t ...