Skip to content

Commit 4c106f3

Browse files
Meir017kblok
authored andcommitted
Implement ElementHandle.QuerySelectorAsync (a.k.a. $) (#218)
1 parent ba9c819 commit 4c106f3

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
using System;
2+
using System.Threading.Tasks;
3+
using Xunit;
4+
5+
namespace PuppeteerSharp.Tests.ElementHandleTests
6+
{
7+
[Collection("PuppeteerLoaderFixture collection")]
8+
public class QuerySelectorTests : PuppeteerPageBaseTest
9+
{
10+
[Fact]
11+
public async Task ShouldQueryExistingElement()
12+
{
13+
await Page.GoToAsync(TestConstants.ServerUrl + "/playground.html");
14+
await Page.SetContentAsync("<html><body><div class=\"second\"><div class=\"inner\">A</div></div></body></html>");
15+
var html = await Page.QuerySelectorAsync("html");
16+
var second = await html.QuerySelectorAsync(".second");
17+
var inner = await second.QuerySelectorAsync(".inner");
18+
var content = await Page.EvaluateFunctionAsync<string>("e => e.textContent", inner);
19+
Assert.Equal("A", content);
20+
}
21+
22+
[Fact]
23+
public async Task ShouldReturnNullForNonExistingElement()
24+
{
25+
await Page.SetContentAsync("<html><body><div class=\"second\"><div class=\"inner\">B</div></div></body></html>");
26+
var html = await Page.QuerySelectorAsync("html");
27+
var second = await html.QuerySelectorAsync(".third");
28+
Assert.Null(second);
29+
}
30+
}
31+
}

lib/PuppeteerSharp/ElementHandle.cs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,12 @@ public async Task PressAsync(string key, PressOptions options = null)
176176
await Page.Keyboard.PressAsync(key, options);
177177
}
178178

179-
internal async Task<ElementHandle> QuerySelectorAsync(string selector)
179+
/// <summary>
180+
/// The method runs <c>element.querySelector</c> within the page. If no element matches the selector, the return value resolve to <c>null</c>.
181+
/// </summary>
182+
/// <param name="selector">A selector to query element for</param>
183+
/// <returns>Task which resolves to <see cref="ElementHandle"/> pointing to the frame element</returns>
184+
public async Task<ElementHandle> QuerySelectorAsync(string selector)
180185
{
181186
var handle = await ExecutionContext.EvaluateFunctionHandleAsync(
182187
"(element, selector) => element.querySelector(selector)",

0 commit comments

Comments
 (0)