--- title: Element methods weight: 4 --- All `Spatie\Html\Elements` have some methods that make working with elements easy. All these methods can be chained together fluently and every method will return a new `Element` instance. This way you can preserve the original `Element` if necessary. ## Available methods - [`attribute()`](#codeattributecode) - [`attributes()`](#codeattributescode) - [`forgetAttribute()`](#codeforgetattributecode) - [`getAttribute()`](#codegetattributecode) - [`class()`](#codeclasscode) - [`id()`](#codeidcode) - [`data()`](#codedatacode) - [`child()` and `children()`](#codechildcode-and-codechildrencode) - [`prependChild()` and `prependChildren()`](#codeprependchildcode-or-codeprependchildrencode) - [`text()`](#codetextcode) - [`if()`](#codeifcode) - [`open()`](#codeopencode) - [`close()`](#codeclosecode) - [`render()`](#coderendercode) You can also call all those methods with the suffix `If` in order to execute the method only if the first parameter is `true`. ```php echo Div::classIf(true, 'row'); // "
" echo Div::classIf(false, 'row'); // "" echo Div::attributeIf(50 > 100, 'data-custom', 'Attribute value'); // "" ``` ## `attribute()` Sets an attribute on the element: ```php echo Div::attribute('data-custom', 'Attribute value'); // "" ``` ## `attributes()` Sets multiple attributes from an array or collection: ```php echo Div::attributes(['data-id' => '123', 'data-username' => 'John']); // "" ``` ## `forgetAttribute()` Remove an attribute from an element: ```php echo Div::attribute('data-custom', 'Attribute value') ->forgetAttribute('data-custom'); // "" ``` ## `getAttribute()` Get the value of an element's attribute: ```php echo Div::attribute('data-custom', 'Attribute value') ->getAttribute('data-custom'); // "data-custom" ``` You may also specify a fallback value: ```php echo Div::getAttribute('data-username', 'Unknown'); // "Unknown" ``` ## `class()` Adds a class to the element. ```php echo Div::class('btn'); // "" ``` ## `id()` Sets the id of the element overwriting any previously set `id`s: ```php echo Div::id('btn-123'); // "" ``` ## `data()` Add a data- attribute: ```php echo Div::data('btn', 123); // "" ``` ## `child()` and `children()` Adds one or more child elements to the element: ```php echo Div::child(P::text('This is the first paragraph')) // "This is the first paragraph
This is the first paragraph
Span content` element will be created for each string and added as a child of `
...
...
...
First
Second
First child
" ``` In combination with the `close()` method this can be really useful for rendering forms: ```html {{ Form::action('/post-url')->method('POST')->open() }} {{ Form::close() }} ``` ## `close()` Returns the elements closing tag as a `Illuminate\Support\HtmlString` (if the element is not a void element like for example `First child