Skip to content

Commit c570b5f

Browse files
committed
Add HasClass extension method
This is a common enough check on web elements that it deserves an easy built-in method.
1 parent 6b7691c commit c570b5f

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

src/Tests/HtmlTests.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,5 +98,19 @@ public void HtmlSettings()
9898
Assert.Equal("Wikipedia", central?.Value);
9999
}
100100

101+
[Fact]
102+
public void HasCssClass()
103+
{
104+
// We wrap the doc with hml>body automatically, so we need to select the div
105+
var div = HtmlDocument.Parse(
106+
"""
107+
<div class="foo bar baz" />
108+
""")
109+
.CssSelectElement("div");
110+
111+
Assert.True(div.HasClass("foo"));
112+
Assert.True(div.HasClass("bar"));
113+
}
114+
101115
string File(string path) => new Uri("file://" + new FileInfo(path).FullName).AbsoluteUri;
102116
}

src/Web/CssSelectorExtensions.cs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,15 @@ public static IEnumerable<XElement> CssSelectElements(this XNode? node, string e
4949
return node.XPathSelectElements(xpath, new CssContext());
5050
}
5151

52+
/// <summary>
53+
/// Determines whether the <see cref="XNode"/> has the specified class.
54+
/// </summary>
55+
public static bool HasClass(this XNode? node, string className)
56+
{
57+
var element = node as XElement;
58+
return element?.Attribute("class")?.Value.Split(' ').Contains(className) ?? false;
59+
}
60+
5261
// The custom context allows resolving the fn:sum which properly implements the XPath 2.0 fn:sum
5362
// see https://www.w3.org/TR/xquery-operators/#func-sum.
5463
class CssContext : XsltContext

0 commit comments

Comments
 (0)