pp-ref
The pp-ref
attribute allows you to mark DOM elements with a reference key that can later be accessed programmatically using the pphp.ref()
function. This is ideal for use cases where you need imperative control over elements—such as focusing, measuring, scrolling, or modifying classes.
Use Cases
Use pp-ref
when you want to:
- Programmatically focus an input element
- Scroll to a specific section on interaction
- Access element dimensions or manual styling
- Work with a collection of matching elements using the same reference key
Syntax
pp-ref="myRef"
— Marks the element with a reference key.pphp.ref('myRef')
— Retrieves the element(s) with that key.pphp.ref('myRef', 0)
— Retrieves a specific indexed element if multiple exist.
Behavior
- Each
pp-ref
key is collected during hydration and removed from the DOM to avoid duplication. - If only one element has the given key,
pphp.ref()
returns a singleHTMLElement
. - If multiple elements share the key, an array
HTMLElement[]
is returned. - If an index is specified, only that element is returned—an error is thrown if the index is out of bounds.
- If no elements are found with the given key, an error is thrown.
Example Usage
<input type="text" pp-ref="userInput" placeholder="Type your name..." />
<button onclick="() => pphp.ref('userInput').focus()">
Focus Input
</button>
Multiple Elements with Same Ref
<div pp-ref="item">Item 1</div>
<div pp-ref="item">Item 2</div>
<div pp-ref="item">Item 3</div>
<script>
const allItems = pphp.ref('item'); // HTMLElement[]
const secondItem = pphp.ref('item', 1); // HTMLElement for "Item 2"
console.log(allItems.length); // 3
</script>
When the same pp-ref
value is used for multiple elements, you can access them as a list or by index. This is useful for repeatable structures or batch processing.