Skip to content
Twilight React Playground
ثيم رائدaren

attrs, clearAttrs (DOM)

functionAdvancedbrowser

Applies html and body attributes straight to the live document, and removes them again; for browser-only apps without TwilightProvider.

import { attrs, clearAttrs } from '@salla.sa/twilight-theme-engine/dom';

In plain words

attrs() from /dom is the plain-JavaScript version: no React, no provider. It puts classes and attributes directly on document.documentElement (the <html> element) and document.body, and remembers what it set, so the next call first removes those. clearAttrs() removes them all.

It is meant for apps that render only in the browser and do not use TwilightProvider. A theme never needs it: inside a theme, call useDocumentClass().

Signature

function attrs(descriptor: DocumentElementDescriptor): void   // does nothing without a document
function clearAttrs(): void

Example

src/pages/product.ts (a browser-only app)
import { attrs, clearAttrs } from '@salla.sa/twilight-theme-engine/dom';

export function enterProductPage() {
  attrs({
    html: { lang: 'ar', dir: 'rtl' },
    body: { class: 'page-product', 'data-page': 'product' },
  });
}

export function leaveProductPage() {
  clearAttrs();
}

How it behaves

  • It records what it applied, as JSON, in a data-de-managed attribute on each element. The next call removes those classes and attributes, then applies the new ones; anything it did not set is left alone.

  • Without a document (on the server) both functions return at once, so nothing they set is in server-rendered HTML.

  • There is no live demo on this page: run inside the playground, it would remove the lang and dir of the page itself (see the gotcha).

Gotchas

  • Never call it in a TwilightProvider app. The provider's DocumentClassProvider syncs the same two elements through the same data-de-managed record (syncAttrsToElement in src/utils/document-class.ts). attrs() first removes what the provider applied, <html lang dir> and body classes such as rtl and salla-<theme> included, and the provider removes yours at its next sync. Use useDocumentClass() from /hooks/useDocumentClass.

  • Calls do not add up: a second call from elsewhere removes what the first one set. Build one descriptor with everything and apply it once.

Related

Source and docs