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