Skip to content

Instantly share code, notes, and snippets.

@TheOnlyWayUp
Last active August 21, 2022 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheOnlyWayUp/e1e78bedaafc19fef527fd82e6cefa09 to your computer and use it in GitHub Desktop.
Save TheOnlyWayUp/e1e78bedaafc19fef527fd82e6cefa09 to your computer and use it in GitHub Desktop.
The aim of this gist is to explain how one can modify attributes in their HTML (<html>) tag when working with a svelte project.

Description - The aim of this gist is to explain how one can modify attributes in their HTML (<html>) tag when working with a svelte project.

A common use-case for modifying the attributes of the <HTML> tag, is to change the lang attribute.

<html lang="en">

Or, in my case, I had to change the theme of the component library I was using (DaisyUI).

<html data-theme="business">

For example ^^

Svelte doesn't make this completely obvious, and it was hard trying to search for a solution due to the synonymity of HTML Tags (Leading to results about <p>, <h1>, ...) vs the <HTML> Tag. Which prompted me to make this gist, to help anyone else facing a similar issue.

In essence, you'll need to make slight modifications to your index.js and App.svelte files, which will be detailed in the below files.


If this helped you, a follow on My Github would be greatly appreciated :)


Resources

<script>
export let HTMLParent; <!-- Declares HTMLParent as a prop -->
let DataTheme = "business";
HTMLParent.setAttribute('data-theme', DataTheme) <!-- Sets the data-theme attribute on the HTML Tag to the value of DataTheme, leading to `<HTML data-theme="business">`.
</script>
<!--
That's it, we've managed to grab and modify the top-level <HTML> Tag. You can make further modifications to it by accessing the HTMLParent variable
- Reference for `HTMLParent` variable's methods - https://developer.mozilla.org/en-US/docs/Web/API/Element
-->
import App from "./App.svelte";
const app = new App({
target: document.body,
props: {
HTMLParent: document.getElementsByTagName("html")[0] // Passes the first found `<HTML>` tag as a prop to the App component
}
});
export default app;
@TheOnlyWayUp
Copy link
Author

Files in order -

  • README.md
  • index.js
  • App.svelte

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment