FluentDOM\Query::attr PHP Method

attr() public method

Access a property on the first matched element or set the attribute(s) of all matched elements
public attr ( string | array $attribute, variadic<[callable | string]> $arguments ) : Query | string
$attribute string | array attribute name or attribute list
$arguments variadic<[callable | string]>
return Query | string attribute value or $this
    public function attr($attribute, ...$arguments)
    {
        if (count($arguments) == 0 && is_string($attribute)) {
            //empty value - read attribute from first element in list
            $attribute = (new QualifiedName($attribute))->name;
            $node = $this->getFirstElement();
            if ($node && $node->hasAttribute($attribute)) {
                return $node->getAttribute($attribute);
            }
            return NULL;
        } else {
            $attributes = $this->getSetterValues($attribute, isset($arguments[0]) ? $arguments[0] : NULL);
            // set attributes on each element
            foreach ($attributes as $key => $value) {
                $name = (new QualifiedName($key))->name;
                $callback = Constraints::isCallable($value);
                $this->each(function (\DOMElement $node, $index) use($name, $value, $callback) {
                    $node->setAttribute($name, $callback ? (string) $callback($node, $index, $node->getAttribute($name)) : (string) $value);
                }, TRUE);
            }
        }
        return $this;
    }

Usage Example

Example #1
0
 /**
  * Set the attribute on all selected element nodes
  *
  * @see ArrayAccess::offsetSet()
  * @see FluentDOM::attr()
  * @example properties/attr-set.php Usage: Set attribute property
  * @param string $name
  * @param string $value
  */
 public function offsetSet($name, $value)
 {
     $this->_fd->attr($name, $value);
 }