diff --git a/js/modules/k6/html/element.go b/js/modules/k6/html/element.go
index ad80a701546b..022531b9a391 100644
--- a/js/modules/k6/html/element.go
+++ b/js/modules/k6/html/element.go
@@ -246,6 +246,18 @@ func (e Element) IsSameNode(v goja.Value) bool {
return false
}
+// Selection returns a Selection object based on the current Element.
+//
+// This function is used to create a Selection object that represents the same HTML
+// content as the Element. It is useful for performing operations or manipulations
+// on the HTML content within the scope of this Element.
+//
+// Example:
+// sel := element.Selection()
+func (e Element) Selection() Selection {
+ return *e.sel
+}
+
func (e Element) GetElementsByClassName(name string) []goja.Value {
return elemList(Selection{e.sel.rt, e.sel.sel.Find("." + name), e.sel.URL})
}
diff --git a/js/modules/k6/html/element_test.go b/js/modules/k6/html/element_test.go
index 144f21eb8ef3..f1f2fd03e314 100644
--- a/js/modules/k6/html/element_test.go
+++ b/js/modules/k6/html/element_test.go
@@ -228,6 +228,15 @@ func TestElement(t *testing.T) {
assert.Contains(t, nodes[3].Export().(Element).TextContent(), "Maecenas augue ligula")
}
})
+ t.Run("Selection", func(t *testing.T) {
+ t.Parallel()
+ rt := getTestRuntimeWithDoc(t, testHTMLElem)
+
+ v, err := rt.RunString(`doc.find('div').get(0).selection().find('h2').text()`)
+ if assert.NoError(t, err) {
+ assert.Equal(t, "Nullam id nisi eget ex pharetra imperdiet.", v.String())
+ }
+ })
t.Run("ClassList", func(t *testing.T) {
t.Parallel()
rt := getTestRuntimeWithDoc(t, testHTMLElem)