2018-09-18 22:42:38 +02:00
|
|
|
package html
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/core"
|
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/values"
|
|
|
|
)
|
|
|
|
|
2018-10-07 04:33:39 +02:00
|
|
|
/*
|
|
|
|
* Finds an element by a given CSS selector.
|
|
|
|
* Returns NONE if element not found.
|
|
|
|
* @param docOrEl (HTMLDocument|HTMLElement) - Parent document or element.
|
|
|
|
* @param selector (String) - CSS selector.
|
|
|
|
* @returns (HTMLElement | None) - Returns an HTMLElement if found, otherwise NONE.
|
|
|
|
*/
|
|
|
|
func Element(_ context.Context, args ...core.Value) (core.Value, error) {
|
|
|
|
el, selector, err := queryArgs(args)
|
2018-09-18 22:42:38 +02:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return values.None, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return el.QuerySelector(selector), nil
|
|
|
|
}
|
|
|
|
|
2018-10-07 04:33:39 +02:00
|
|
|
func queryArgs(args []core.Value) (values.HTMLNode, values.String, error) {
|
|
|
|
err := core.ValidateArgs(args, 2, 2)
|
2018-09-18 22:42:38 +02:00
|
|
|
|
|
|
|
if err != nil {
|
2018-10-07 04:33:39 +02:00
|
|
|
return nil, values.EmptyString, err
|
2018-09-18 22:42:38 +02:00
|
|
|
}
|
|
|
|
|
2018-10-07 04:33:39 +02:00
|
|
|
err = core.ValidateType(args[0], core.HTMLDocumentType, core.HTMLElementType)
|
2018-09-18 22:42:38 +02:00
|
|
|
|
2018-10-07 04:33:39 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, values.EmptyString, err
|
2018-09-18 22:42:38 +02:00
|
|
|
}
|
|
|
|
|
2018-10-07 04:33:39 +02:00
|
|
|
err = core.ValidateType(args[1], core.StringType)
|
2018-09-18 22:42:38 +02:00
|
|
|
|
2018-10-07 04:33:39 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, values.EmptyString, err
|
2018-09-18 22:42:38 +02:00
|
|
|
}
|
|
|
|
|
2018-10-07 04:33:39 +02:00
|
|
|
return args[0].(values.HTMLNode), args[1].(values.String), nil
|
2018-09-18 22:42:38 +02:00
|
|
|
}
|