---
title: "Toggle a CSS class on an HTML element in C#"
url: https://recursiveai.org/onehtml/cookbook/toggle-html-class-in-mutable-dom/
description: "Toggle a CSS class on an HTML element in C# with onehtml. Add or remove one class without replacing the others, then commit and write the new markup."
version: "1.7.0"
---

# 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.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneHtml) · [GitHub](https://github.com/recursive-ai-oss/onehtml-csharp) · [Docs](https://recursiveai.org/onehtml/docs/) · [Download example (.zip)](https://recursiveai.org/onehtml/cookbook/toggle-html-class-in-mutable-dom/toggle-html-class-in-mutable-dom.zip)

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

```shell
dotnet add package RecursiveAI.OneHtml
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
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](https://recursiveai.org/onehtml/cookbook/toggle-html-class-in-mutable-dom/toggle-html-class-in-mutable-dom.zip) 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.

```csharp
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:

```csharp
var present = button.ToggleClass("tab", force: false);
doc.Commit();
Console.WriteLine(present);
Console.WriteLine(button.HasClass("tab"));
```

```text
False
False
```

## Related recipes

- [Edit HTML without reformatting it](https://recursiveai.org/onehtml/cookbook/edit-html-csharp-lossless/)
- [Restyle CSS after a DOM edit in C#](https://recursiveai.org/onehtml/cookbook/incrementally-restyle-after-dom-edit/)

## 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()`](https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/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`.
