Javascript : How to Access DOM

Hi all,

Having a python Background, I am pretty new in Javascript. All I am trying to do is access a DOM element**

From what I understood, you can not use Jquery to get access to DOM elements since it is not compliant with React (What is Plotly / Dash build on).

So I tried a couple of options :

1 - Access Element in simple JS :

var element = document.getElementById(id); However, I keep getting null results, since the page is loaded after the script is launched from my understanding. So my script var never finds the elements.

2 - I tried using React.JS for the first time, but quickly gave up since it seems to be a bit of a learning curve for something as simple as accessing a DOM elements

3 - I actually did not try html.Script() yet.

Many thanks in advance to whoever will take the time to read and reply,

** DOM : Class name, Id, Tags, Attributs of your html page - https://www.w3schools.com/js/js_htmldom.asp

Quentin

I am currently on the same issue. Did you find anything?

You could create an event listener and that could then dispatch whatever JS you are looking to do.

I had a specific use case where I used dcc.Locaton’s hash value as a trigger and updated the hash in a callback and that worked just fine. Can’t say anything about any of the other events but maybe you might want to try the onload eventhandler?

Hey, @mbkupfer,

Is this working on a multi-page app? It sounds to be a quite good workaround if this works.

@rahul27593, I finally used the visdcc.run_js module created by @jimmybow. It is a great feature, and enables you to run JS within your dash app. If you want more info : https://github.com/jimmybow/visdcc

Here is an example :

app.layout = html.Div([
html.Button('open url', id = 'button'),
visdcc.Run_js(id = 'javascript')
])
           
@app.callback(
    Output('javascript', 'run'),
    [Input('button', 'n_clicks')])
def myfun(x): 
    if x: 
        return "window.open('https://yahoo.com/')"
    return "" 

Quentin

1 Like

I don’t see why it wouldn’t. Just add an event listener to determine the dash app.

You do mention that you are still new to JS and looks like you were able to solve with Visdcc. If that is working for you then I’d just stick with that.

@qdumont @mbkupfer your help is much appreciated. Thank you:)
The reason why we are unable to access DOM is the incompatible issue between ReactJS and custom JS.
Source