github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/html/attr_get.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_GET gets single or more attribute(s) of a given element.
    12  // @param {HTMLPage | HTMLDocument | HTMLElement} node - Target node.
    13  // @param {String, repeated} attrNames - Attribute name(s).
    14  // @return {Object} - Key-value pairs of attribute values.
    15  func AttributeGet(ctx context.Context, args ...core.Value) (core.Value, error) {
    16  	err := core.ValidateArgs(args, 2, core.MaxArgs)
    17  
    18  	if err != nil {
    19  		return values.None, err
    20  	}
    21  
    22  	el, err := drivers.ToElement(args[0])
    23  
    24  	if err != nil {
    25  		return values.None, err
    26  	}
    27  
    28  	names := args[1:]
    29  	result := values.NewObject()
    30  	attrs, err := el.GetAttributes(ctx)
    31  
    32  	if err != nil {
    33  		return values.None, err
    34  	}
    35  
    36  	for _, n := range names {
    37  		name := values.NewString(n.String())
    38  		val, exists := attrs.Get(name)
    39  
    40  		if exists {
    41  			result.Set(name, val)
    42  		}
    43  	}
    44  
    45  	return result, nil
    46  }