How to Access DOM

I can’t seem to access DOM elements directly in dash, is there any way to solve it?

example app.py

from dash import Dash, html, dcc

app = Dash(__name__)


app.layout = html.Div(children=[
    html.H1(children='Hello Dash',id = "test")
])

if __name__ == '__main__':
    app.run(debug=True)

example assets/main.js

window.onload = function() {
    let el = document.getElementById("test");
    console.log(el);
};

Hello @Liripo,

This is due to how dash loads.

It initially loads a basic layout, then renders the layout. At the time of the document load, the dash app hasn’t been rendered.

This is why using clientside callbacks based upon the component id is a good way to trigger onload scripts.

1 Like

Thanks for the answer, then it seems I can’t scope the component id directly.

I’m confused by what you mean by this, could you please elaborate?

1 Like

Oh, I know how to do it, no other questions.
example app.py

from dash import Dash, html, dcc, callback,Input ,Output,clientside_callback

app = Dash(__name__)


app.layout = html.Div(children=[
    html.H1(children='Hello Dash',id = "test")
])

clientside_callback(
    """
    function(id) {
        let el = document.getElementById("test");
        console.log(el);
        return window.dash_clientside.no_update
    }
    """,
    Output("test","id"),
    Input("test","id"),
)

if __name__ == '__main__':
    app.run(debug=True)

1 Like