Tom Rider
Tom Rider

Reputation: 2805

Accessing style attribute individually

I am using HtmlAgilityPack in c#. I created a div element with some attribute like,

HtmlNode div = HtmlNode.CreateNode("<div></div>");
div.Attributes.Add("style","width:100px;height:100px;color:red;position:absolute;");

Now I want to know that is there any method in HtmlAgilityPack by with i can access the style Attributes individually, like we do in jQuery :

         $("div").width(); or $("div").css("width");

Upvotes: 1

Views: 1092

Answers (1)

Jamie Treworgy
Jamie Treworgy

Reputation: 24334

You could try using CsQuery, which is in fact like jQuery:

CQ div = CQ.Create("<div></div>");

div.CssSet( new {
    width="100px",
    height="100px",
    color="red",
    position="absolute"
});

//.. or

div.Css("width","100px").Css( ... ) ...

string width = div.Css("width");       // width=="100px"

int widthInt = div.Css<int>("width");  // widthInt==100

It implements every DOM manipulation method of jQuery, so the API should be very familiar. It also provides an implemention that mostly mimics the browser DOM, e.g.

var nodeName = div[0].NodeName;         // nodeName=="DIV";

div[0].AppendChild(div.Document.CeateElement("span"));   // add a span child 

There are a couple exceptions, CssSet is one of them, where the overloaded methods in javascript didn't work out in C# so a different method had to be used. (The other one is AttrSet when setting from an object). It's also got extensive unit test coverage, including much of the test suite from jQuery ported to C#, and selectors are much faster than HTML Agility Pack (not to mention a lot less confusing since they're just CSS) thanks to a subselect-capable index.

Upvotes: 2

Related Questions