Recursive AI

Toggle a CSS class on an HTML element in C#

onehtml is a free, open-source HTML library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

ToggleClass flips one class and leaves the other class names in place.

Terminal
dotnet add package RecursiveAI.OneHtml

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using RecursiveAI.OneHtml.Mutation;
 
var doc = MutableDocument.Parse(
    "<button class=tab>Inbox</button>");
// html → body → button
var button = doc.DocumentElement.LastChild.FirstChild;
button.ToggleClass("active");
doc.Commit();
var classes = button.GetAttribute("class");
Console.WriteLine(classes);

The example is the full program below: unzip it and dotnet run. To run only the code above, paste it into Program.cs of a new dotnet new console project and dotnet run.

The button keeps tab and gains active:

Text
tab active

The full program

Start with <button class=tab>Inbox</button>. Toggle active twice, committing each edit. Print both the updated button markup and the class tokens added or removed in each commit.

C#
using RecursiveAI.OneHtml.Mutation;
 
var doc = MutableDocument.Parse("<button class=tab>Inbox</button>");
// html → body → button
var button = doc.DocumentElement.LastChild.FirstChild;
 
foreach (var turn in new[] { "On", "Off" })
{
    var active = button.ToggleClass("active");
    var commit = doc.Commit();
    Console.WriteLine($"{turn}: {active}");
    Console.WriteLine(doc.SerializeNode(button));
    var change = commit.Changes.Classes[0];
    foreach (var name in change.Added)
        Console.WriteLine($"Added: {name}");
    foreach (var name in change.Removed)
        Console.WriteLine($"Removed: {name}");
}

dotnet run prints:

Text
On: True
<button class="tab active">Inbox</button>
Added: active
Off: False
<button class="tab">Inbox</button>
Removed: active

Here the parser puts the button first in <body>. On other input, don’t assume the same child position. Locate the element on a committed snapshot (for example, by ID) and use WorkingSnapshot.ToMutable to get its editable handle. ToggleClass throws a DomException with kind InvalidCharacter if you pass an empty token or one containing ASCII whitespace.

Variations

Set a class from a Boolean instead of flipping it. Replace the loop in the full program with this code. It removes tab, regardless of whether the class was already absent:

C#
var present = button.ToggleClass("tab", force: false);
doc.Commit();
Console.WriteLine(present);
Console.WriteLine(button.HasClass("tab"));
Text
False
False

The short answer

Call element.ToggleClass("active") on a onehtml MutableNode, then doc.Commit() on its MutableDocument. If active was missing, the method adds it and returns true; if it was present, the method removes it and returns false. The return value says whether the class is present afterward, not whether the call wrote anything. Use SerializeNode when you need the resulting HTML for just that element and its children.

What does class list toggle do to the other classes?

onehtml’s ToggleClass follows the token-list behavior of classList.toggle(). Pass a class name without the dot you would use in a CSS selector. active and inactive are separate tokens, so toggling one doesn’t alter the other. An edit that changes the set rewrites the attribute with normalized spacing and removes duplicates while keeping the order of first appearance. A call that leaves the set unchanged doesn’t rewrite it.

How do you add or remove a class without toggling it?

Use the force argument when the class should reflect state your application already knows. For example, if a record is no longer selected, pass false for its selected class. Passing false a second time still leaves the class absent. Without force, the second call would undo the first. For an explicit add or remove, AddClass and RemoveClass also take a single token; unlike ToggleClass, their results report whether that operation changed the class list.

Why does toggling a CSS class have no visible effect?

This code edits a parsed HTML tree, not the DOM of a page already open in a browser. To see the change in a browser, render the updated markup there. A class is a name, not a style declaration: an active class only changes the appearance if an applicable CSS rule uses it. In C#, read HasClass to check the working node immediately. Call Commit() before reading a new immutable snapshot or looking for the change in commit.Changes.Classes.

All onehtml recipes