Roland Weigelt

Born to Code


.NET related Links


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)

Posted: Nov 27 2006, 05:25 PM by WeigeltRo | with 5 comment(s) |
Filed under: , ,


markus said:

Do you know what style property is called? SetAttribute("Style", "position:absolute....") does not work.

# January 8, 2007 10:08 AM

WeigeltRo said:

I had a similar problem - the style seems to be special. The HtmlElement has an extra Style property (which is what I'm using in my code)


# January 8, 2007 3:57 PM

rebel said:

myHtmlElement.Attributes ["class"] = "hidden";

# January 30, 2007 11:54 AM

WeigeltRo said:

@rebel: Interesting...

So HtmlElement is not exactly a good example for what is called "discoverability" in API design, with three different approaches ("Set" method call, specific property, and Attributes collection) confusing the API users...

# January 30, 2007 5:23 PM

uday said:

thanks..that solved my problem..i was wondering what was wrong with my code!

# March 9, 2007 9:58 AM