#Is there a way to get the 'data-astro-cid-*' attribute server side in Astro?
3 messages · Page 1 of 1 (latest)
Hi @honest ibex. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Astro does not provide a direct way to access the data-astro-cid-* attribute server-side. This attribute is used for scoped styling in Astro and is automatically added to the elements during the build process.
However, if you need to select elements with JavaScript, you can use other attributes or classes. For instance, you can use data-* attributes to store the value of variables in your HTML output. Scripts, including custom elements, can then read these attributes using an element’s dataset property once your HTML loads in the browser.
Here's an example from the Astro documentation:
---const { message = 'Welcome, world!' } = Astro.props;---
<!-- Store the message prop as a data attribute. -->
<astro-greet data-message={message}>
<button>Say hi!</button>
</astro-greet>
<script>
class AstroGreet extends HTMLElement {
constructor() {
super();
// Read the message from the data attribute.
const message = this.dataset.message;
const button = this.querySelector('button');
button.addEventListener('click', () => {
alert(message);
});
}
}
customElements.define('astro-greet', AstroGreet);
</script>
In this example, a message prop is stored in a data-message attribute, so the custom element can read this.dataset.message and get the value of the prop in the browser.