Last active
December 11, 2024 20:13
-
-
Save hamzaaitbrik/0d43bd5a8928a80a7291413538282bc6 to your computer and use it in GitHub Desktop.
I do web automation with Selenium, and it's really hard dealing with elements nested deeply into shadowRoots. I wrote this script to return a web element with a specific tag name that has a specific value to a specific attribute. I usually use this to reutrn my target element that I can't access directly with Python's web automation frameworks, …
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// !! code snippet made by hamzaaitbrik @ GitHub !! | |
(() => { | |
const matchedElements = []; | |
function traverse(node) { | |
// Check if the node is an element node and has the specified href | |
if (node.nodeType === Node.ELEMENT_NODE && node.tagName === 'TAGNAME') { | |
if (node.getAttribute('ATTRIBUTE') === 'VALUE') { | |
matchedElements.push(node); | |
} | |
} | |
// If the node is a shadow host, traverse its shadow root | |
if (node.shadowRoot) { | |
traverse(node.shadowRoot); | |
} | |
// Recursively traverse child nodes | |
node.childNodes.forEach(child => traverse(child)); | |
} | |
// Start traversing from the document body | |
traverse(document.body); | |
const targetElement = matchedElements[0]; | |
return targetElement; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment