Code works in console but not in streamlit

Hi all,

This JS code works flawlessly when ran from console, but when I try to inject it by using st.components.v1.htm and wrapping it in script tags, nothing is happening. How in the world do I get this to work?
Thank you


        // Specify the section to highlight    
        var section = document.querySelector(".main.css-k1vhr4.egzxvld5");

        if (section) {
        // Specify the keyword you want to highlight
        var keyword = "page";

        // Create a regular expression to match the keyword (case-insensitive)
        var regex = new RegExp(keyword, "gi");

        // Get all text nodes within the section
        var textNodes = document.createTreeWalker(section, NodeFilter.SHOW_TEXT, null, false);
        var node;

        // Iterate through the text nodes and highlight the keyword where found
        while (node = textNodes.nextNode()) {
            if (regex.test(node.nodeValue)) {
            var highlightedText = node.nodeValue.replace(regex, '<span style="background-color: yellow;">$&</span>');
            var wrapper = document.createElement('div');
            wrapper.innerHTML = highlightedText;
            node.parentNode.replaceChild(wrapper, node);

}, 3000);

Components exist in an iframe. You’ll need parent.document.querySelector to reach out of the iframe into the app as a whole.

Try replacing each document with parent.document.

1 Like

Oh my goodnes mathcatsand, can’t express my gratitude!! I’ve been stumped on this one for about 5 hours! You’re a blessing. It worked!!

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.