github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/html/attr_query.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  // ATTR_QUERY finds a single or more attribute(s) by an query selector.
    12  // @param {HTMLPage | HTMLDocument | HTMLElement} node - Target node.
    13  // @param {String} selector - Query selector.
    14  // @param {String, repeated} attrName - Attr name(s).
    15  // @return {Object} - Key-value pairs of attribute values.
    16  func AttributeQuery(ctx context.Context, args ...core.Value) (core.Value, error) {
    17  	err := core.ValidateArgs(args, 2, core.MaxArgs)
    18  
    19  	if err != nil {
    20  		return values.None, err
    21  	}
    22  
    23  	parent, err := drivers.ToElement(args[0])
    24  
    25  	if err != nil {
    26  		return values.None, err
    27  	}
    28  
    29  	selector, err := drivers.ToQuerySelector(args[1])
    30  
    31  	if err != nil {
    32  		return values.None, err
    33  	}
    34  
    35  	found, err := parent.QuerySelector(ctx, selector)
    36  
    37  	if err != nil {
    38  		return values.None, err
    39  	}
    40  
    41  	el, err := drivers.ToElement(found)
    42  
    43  	if err != nil {
    44  		return values.None, err
    45  	}
    46  
    47  	names := args[2:]
    48  	result := values.NewObject()
    49  	attrs, err := el.GetAttributes(ctx)
    50  
    51  	if err != nil {
    52  		return values.None, err
    53  	}
    54  
    55  	for _, n := range names {
    56  		name := values.NewString(n.String())
    57  		val, exists := attrs.Get(name)
    58  
    59  		if exists {
    60  			result.Set(name, val)
    61  		}
    62  	}
    63  
    64  	return result, nil
    65  }