Skip to content

[Web] How to modify <html> tag attributes programmatically? #4162

Answered by wiseaidev
AndrewVetovitz asked this question in Q&A
Discussion options

You must be logged in to vote

Hello!

To modify the attributes of the <html> tag, you can use the web-sys crate to retrieve the document_element and downcast it to an HtmlElement as follows:

use web_sys::{wasm_bindgen::JsCast, HtmlElement};

let html_element = web_sys::window()
    .expect("Window not found")
    .document()
    .expect("Document not found")
    .document_element()
    .expect("Document element not found")
    .dyn_into::<HtmlElement>()
    .expect("Failed to cast to HtmlElement");

Once you have the HtmlElement, you can set an attribute like this:

html_element
    .set_attribute("data-theme", "dark")
    .expect("Failed to set attribute");

I learned this approach while building theme.

Note: When using w…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@AndrewVetovitz
Comment options

Answer selected by AndrewVetovitz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants