Use QuerySelectors in a page custom code

Hi there ! Has anyone already run into trouble when trying to play with custom JS scripts and querySelectors ? I’m going crazy with that one. I have a querySelector that works fine in my browser console, but won’t return anything but null when placed in a script.

I highly suspect the problem is linked to precedence, with the script running before my content is fully loaded, so I’ve conditioned it to run on the “load” event of my window, which to my understanding is the latest event I could rely on, but it still doesn’t work. Any help or tips to preserve my sanity ? :slightly_smiling_face:

Here is my code (that doesn’t work) :

<script>
window.addEventListener("load", function() {

    var xxx = document.querySelector('div[data-mappedto="formatted_title"]').getAttribute('data-value');
    console.log(xxx);

}); 
</script>

and the query that works in the console : document.querySelector('div[data-mappedto="formatted_title"]').getAttribute('data-value')

Adding here for visibility too

<script>
    document.addEventListener("DOMContentLoaded", function() {
        const existCondition = setInterval(function() {
            if ($('#selector-goes-here').length) {
                /* Do Your Logic */
                clearInterval(existCondition);
            }
        }, 100);
    });
</script>
1 Like