Automation QA Testing Course Content

Handling Shadow Dom Elements in Selenium

 

What is a Document Object Model (DOM)?

The Document Object Model (DOM) represents the way a web page is accessed and manipulated. It defines the logical structure of the documents and represents the HTML document with a logical tree where each branch of the tree ends and each node contains objects.

DOM methods allow you to programmatically access the tree and change the document’s structure, style, or content.


What is Shadow DOM?

Shadow DOM is a functionality that allows the web browser to render DOM elements without putting them into the main document DOM tree. This creates a barrier between what the developer and the browser can reach; the developer cannot access the Shadow DOM the same way they would with nested elements, while the browser can render and modify that code the same way it would with nested elements.

The Shadow DOM is a way to achieve encapsulation in the HTML document. By implementing it, you can keep the style and behavior of one part of the document hidden and separate from the other code of the same document so that there is no interference.

Shadow DOM allows hidden DOM trees to be attached to elements in the regular DOM tree — the Shadow DOM tree starts with a Shadow Root, underneath which you can attach any element in the same way as the normal DOM.


There are some bits of Shadow DOM terminology to be aware of:

  • Shadow Host: The regular DOM node to which the Shadow DOM is attached.
  • Shadow Tree: The DOM tree inside the Shadow DOM.
  • Shadow Boundary: The place where the Shadow DOM ends and the regular DOM begins.
  • Shadow Root: The root node of the Shadow tree.

What is the Use of Shadow DOM?

Shadow DOM serves for encapsulation. It allows a component to have its own “shadow” DOM tree that can’t be accidentally accessed from the main document, may have local style rules, and more.

Here are some of the essential properties of Shadow DOM:

  • Have their own ids space.
  • Invisible to JavaScript selectors from the main document, such as querySelector.
  • Use styles only from the shadow tree, not from the main document.

Finding Shadow DOM Elements Using Selenium WebDriver

When we try to find Shadow DOM elements using selenium locators, it will throw 'NoSuchElementException'. To access these Shadow DOM elements, we need to use JavascriptExecutor executeScript() function. If you look at the DOM structure, every element that has ShadowDOM also has a shadowRoot property which describes the underlying elements.

We would use the following strategy to access the Shadow DOM locators:




No comments:

Post a Comment

Note: Only a member of this blog may post a comment.