github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/html/element.go (about)

     1  package html
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/MontFerret/ferret/pkg/drivers"
     7  	"github.com/MontFerret/ferret/pkg/runtime/core"
     8  	"github.com/MontFerret/ferret/pkg/runtime/values"
     9  )
    10  
    11  // ELEMENT finds an element by a given CSS selector.
    12  // Returns NONE if element not found.
    13  // @param {HTMLPage | HTMLDocument | HTMLElement} node - Target html node.
    14  // @param {String} selector - CSS selector.
    15  // @return {HTMLElement} - A matched HTML element
    16  func Element(ctx context.Context, args ...core.Value) (core.Value, error) {
    17  	el, selector, err := queryArgs(args)
    18  
    19  	if err != nil {
    20  		return values.None, err
    21  	}
    22  
    23  	return el.QuerySelector(ctx, selector)
    24  }
    25  
    26  func queryArgs(args []core.Value) (drivers.HTMLElement, drivers.QuerySelector, error) {
    27  	err := core.ValidateArgs(args, 2, 2)
    28  
    29  	if err != nil {
    30  		return nil, drivers.QuerySelector{}, err
    31  	}
    32  
    33  	el, err := drivers.ToElement(args[0])
    34  
    35  	if err != nil {
    36  		return nil, drivers.QuerySelector{}, err
    37  	}
    38  
    39  	selector, err := drivers.ToQuerySelector(args[1])
    40  
    41  	if err != nil {
    42  		return nil, drivers.QuerySelector{}, err
    43  	}
    44  
    45  	return el, selector, nil
    46  }