This is the archived version of Roland Weigelt's weblog that ran from 2003 to 2023 at weblogs.asp.net

How to Set the CSS Class on an HtmlElement Instance from C#

I’m currently using the WebBrowser control in a WinForms application as a simple layout engine, as it’s much faster when rendering texts in front of a background image than WinForms (and I need it by the weekend, so I don’t want to take the risk of using it as a learning project for WPF). For my purposes I only need to manipulate some texts – and the CSS class of specific elements on the page.

Now let’s assume you have an DIV tag in your HTML like this:

<div class="someClass">Hello World</div>

and you want to change the CSS class from your C# code. It’s pretty easy, you just have to get a HtmlElement instance representing the tag and use the SetAttribute method. What took me some time to figure out is the problem that if you call

myHtmlElement.SetAttribute("class", "anotherClass");

nothing will happen in the display of your page. The reason for this is that SetAttribute does not actually “set an attribute of a tag”, but a property (representing the attribute) on an object (representing the tag) in the Document Object Model (DOM) – and the property’s name is “className”, not “class”. So the correct code is

myHtmlElement.SetAttribute("className", "anotherClass");

(If you're wondering why SetAttribute didn't complain about using the name "class": the DOM was primarily designed to be used from Javascript, which is a language where any object can be extended by simple setting a property. Sounds a bit strange, but it’s also a feature that can be used for seriously cool stuff)

5 Comments

Comments have been disabled for this content.