Popular Searches
Popular Course Categories
Popular Courses

Understanding DOM

HTML & Web Elements

 

 

 

Understanding DOM

 

 

The DOM (Document Object Model) is one of the most important concepts for Selenium testers because Selenium interacts with web pages through the elements represented in the DOM. Understanding the DOM helps testers inspect web elements, understand parent-child relationships, create reliable locators, work with dynamic elements, troubleshoot automation failures, and understand how browsers represent HTML documents.

 

 

When a browser loads an HTML page, it parses the HTML and creates a structured representation called the DOM tree. Selenium WebDriver can then locate elements within this structure and perform actions such as clicking buttons, entering text, selecting options, reading text, and validating page content.

 

 


 

 

1. What is DOM?

 

 

DOM stands for Document Object Model. It is a programming interface that represents an HTML or XML document as a hierarchical structure of objects called nodes.

 

 

When a browser loads an HTML document, it converts the HTML source into a DOM structure. Each important part of the document, such as elements, attributes, and text, is represented within this structure.

 

 

For Selenium testers, the DOM is important because Selenium WebDriver interacts with the elements represented by the browser's DOM.

 

 

Simple Definition

 

 

The DOM is a tree-like representation of a web page that allows browsers, JavaScript, and automation tools to access and interact with HTML elements.

 

 


 

 

2. Why is DOM Important for Selenium Testers?

 

 

Selenium does not simply interact with the visual appearance of a webpage. It locates and interacts with elements exposed by the browser's document structure.

 

 

 

 

  • Helps identify web elements.

 

 

  • Helps create reliable locators.

 

 

  • Helps understand XPath and CSS selectors.

 

 

  • Helps identify parent-child relationships.

 

 

  • Helps debug element-not-found problems.

 

 

  • Helps handle dynamic web elements.

 

 

  • Helps understand hidden and visible elements.

 

 

  • Helps troubleshoot stale element problems.

 

 

  • Helps understand frames and Shadow DOM.

 

 

  • Helps maintain Selenium automation scripts.

 

 

 

 


 

 

3. HTML vs DOM

 

 

HTML is the markup written by developers to structure a webpage. The DOM is the browser-created object representation of that document.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

HTML DOM
Markup language used to structure webpages. Object-based representation of the document.
Contains tags and attributes. Contains nodes, elements, attributes, and relationships.
Represents the source document. Represents the document as interpreted by the browser.
Usually written by developers. Created and maintained by the browser.
Can be stored as source code. Can be modified dynamically using JavaScript.

 

Example HTML

 

 

<button id="login">Login</button>

 

 

The browser creates a corresponding DOM element that Selenium can locate.

 

 


 

 

4. DOM Tree

 

 

The DOM is commonly represented as a tree because HTML elements have hierarchical relationships.

 

 

Example

 

 

<html>

 


    <head>


        <title>Login Page</title>


    </head>


    <body>


        <div id="login-container">


            <h1>Login</h1>


            <input id="username" type="text">


            <button id="login">Login</button>


        </div>


    </body>


</html>

 

 

The corresponding conceptual DOM structure can be represented as:

 

 

HTML

 


├── HEAD


│   └── TITLE


└── BODY


    └── DIV


        ├── H1


        ├── INPUT


        └── BUTTON

 

 


 

 

5. Document Node

 

 

The document node represents the complete HTML document. It is the top-level entry point of the DOM.

 

 

Document

 


└── HTML


    ├── HEAD


    └── BODY

 

 

In JavaScript, the document object can be used to access and manipulate the webpage.

 

 

document.title

 


document.body


document.getElementById("login")

 

 


 

 

6. DOM Elements

 

 

An element is an individual HTML component represented in the DOM.

 

 

Examples include:

 

 

 

 

  • Button

 

 

  • Input

 

 

  • Heading

 

 

  • Paragraph

 

 

  • Link

 

 

  • Image

 

 

  • Table

 

 

  • Form

 

 

  • Dropdown

 

 

  • Checkbox

 

 

 

 

<input id="username" type="text">

 


<button id="login">Login</button>

 

 

In Selenium, these elements can be represented by WebElement objects.

 

 


 

 

7. DOM Nodes

 

 

A node is a basic unit in the DOM tree. Elements are one type of node, but the DOM can also contain document nodes, text nodes, comment nodes, and attribute information.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Node Type Example
Document Node Complete HTML document
Element Node <button>
Text Node Login
Comment Node <!-- comment -->
Attribute id="login"

 


 

 

8. Parent and Child Relationships

 

 

DOM elements have hierarchical relationships. An element that contains another element is called its parent, while the contained element is called its child.

 

 

<div>

 


    <button>Login</button>


</div>

 

 

Here, the div is the parent and the button is the child.

 

 


 

 

9. Sibling Elements

 

 

Elements that share the same parent are called sibling elements.

 

 

<div>

 


    <input id="username">


    <input id="password">


    <button id="login">Login</button>


</div>

 

 

The username input, password input, and login button are siblings because they share the same parent.

 

 


 

 

10. Ancestor and Descendant

 

 

An ancestor is any element that appears above another element in the DOM hierarchy. A descendant is an element that appears below another element.

 

 

<div class="container">

 


    <form>


        <div class="field">


            <input id="username">


        </div>


    </form>


</div>

 

 

The container div is an ancestor of the input, while the input is a descendant of the container.

 

 


 

 

11. DOM Attributes

 

 

HTML attributes provide additional information about an element.

 

 

<input id="username" name="user" type="text" class="form-control">

 

 

Here, id, name, type, and class are attributes.

 

 

Selenium testers frequently use these attributes to create locators.

 

 


 

 

12. Common Attributes Used for Selenium Locators

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Attribute Example Usage
id id="username" Usually a strong locator when unique and stable.
name name="email" Useful for form fields.
class class="login-button" Useful with CSS selectors or XPath.
type type="submit" Useful for identifying element types.
placeholder placeholder="Enter Email" Useful when stable.
data-* data-testid="login" Often useful for stable automation locators.

 


 

 

13. DOM and Text Nodes

 

 

Text displayed inside an HTML element can be represented as text within the DOM.

 

 

<button>Login</button>

 

 

The word Login is the text content of the button.

 

 

In Selenium, methods such as getText() can be used to retrieve visible text from a WebElement.

 

 


 

 

14. DOM and Selenium WebElement

 

 

Selenium's WebElement represents an element on a webpage. After Selenium finds an element, the returned WebElement can be used to perform actions and retrieve information.

 

 

WebElement loginButton = driver.findElement(By.id("login"));

 


loginButton.click();

 

 

The browser's DOM contains the element, while Selenium provides the WebElement interface for automation interaction.

 

 


 

 

15. DOM and findElement()

 

 

The findElement() method is used to locate a single element using a locator strategy.

 

 

WebElement username = driver.findElement(By.id("username"));

 


username.sendKeys("admin");

 

 

The locator tells Selenium which element to search for in the current page context.

 

 


 

 

16. DOM and findElements()

 

 

The findElements() method is used when multiple matching elements may exist.

 

 

List<WebElement> buttons = driver.findElements(By.tagName("button"));

 



for (WebElement button : buttons) {


    System.out.println(button.getText());


}

 

 


 

 

17. DOM and XPath

 

 

XPath is a locator language that allows Selenium testers to navigate and identify elements in the DOM.

 

 

//button[@id='login']

 

 

This XPath identifies a button whose id attribute is login.

 

 

Text-Based XPath

 

 

//button[text()='Login']

 

 

Contains

 

 

//button[contains(text(),'Login')]

 

 


 

 

18. DOM and CSS Selectors

 

 

CSS selectors provide another powerful way to locate elements in the DOM.

 

 

#login

 


.username


input[type='text']


button.login-button

 

 

CSS selectors are often concise and useful for creating maintainable Selenium locators.

 

 


 

 

19. Inspecting the DOM Using Browser Developer Tools

 

 

Browser Developer Tools are essential for Selenium testers. They allow testers to inspect HTML elements, attributes, styles, events, and the current DOM structure.

 

 

To inspect an element:

 

 

 

 

  1. Open the webpage.

 

 

  1. Right-click the element.

 

 

  1. Select Inspect.

 

 

  1. Developer Tools will highlight the corresponding DOM element.

 

 

  1. Study its tag, attributes, parent, child, and sibling relationships.

 

 

 

 


 

 

20. Elements Panel

 

 

The Elements panel in browser Developer Tools displays the current DOM structure.

 

 

It can be used to inspect:

 

 

 

 

  • HTML tags

 

 

  • Attributes

 

 

  • Parent-child relationships

 

 

  • Classes

 

 

  • IDs

 

 

  • Text content

 

 

  • Dynamic changes

 

 

  • Shadow DOM structures

 

 

 

 


 

 

21. HTML Source vs Current DOM

 

 

One important concept for Selenium testers is the difference between the original HTML source and the current DOM.

 

 

JavaScript can modify the DOM after the page has loaded. Therefore, the current DOM shown in Developer Tools may contain elements or attribute values that were not present in the original server response.

 

 


 

 

22. Dynamic DOM

 

 

Modern web applications frequently modify the DOM dynamically using JavaScript.

 

 

Examples include:

 

 

 

 

  • AJAX requests

 

 

  • React applications

 

 

  • Angular applications

 

 

  • Vue applications

 

 

  • Autocomplete fields

 

 

  • Dynamic tables

 

 

  • Product listings

 

 

  • Popups and modals

 

 

 

 


 

 

23. DOM and AJAX

 

 

AJAX allows webpages to request data from servers without completely reloading the page. The received data can then be used to update the DOM.

 

 

For example, entering a product name into a search box may cause suggestions to appear dynamically.

 

 

User enters text

 


        ↓


AJAX request


        ↓


Server returns data


        ↓


JavaScript processes response


        ↓


DOM is updated


        ↓


New elements appear

 

 


 

 

24. DOM and React Applications

 

 

React applications frequently update the user interface based on application state. Selenium testers should therefore understand that elements may be created, removed, or updated dynamically.

 

 

For automation, testers should focus on stable attributes and reliable synchronization rather than assuming that the DOM remains unchanged.

 

 


 

 

25. DOM and Angular Applications

 

 

Angular applications can dynamically render components and update elements. Elements may appear after asynchronous operations.

 

 

Explicit waits and stable locators are useful when automating such applications.

 

 


 

 

26. DOM and Vue Applications

 

 

Vue applications also update the DOM dynamically when application data changes. Selenium testers should inspect the current DOM and identify stable element attributes for automation.

 

 


 

 

27. Dynamic Elements

 

 

A dynamic element is an element whose properties, position, presence, or state can change during application execution.

 

 

<button id="btn_82736">Login</button>

 

 

If the ID changes every time the page loads, using the complete ID may create a fragile locator.

 

 

A more stable attribute or relationship should be considered when available.

 

 


 

 

28. Stable vs Unstable Locators

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Locator Example Typical Stability
Unique ID By.id("username") High when stable
Data Test ID By.cssSelector("[data-testid='login']") High when intentionally provided for testing
Stable Name By.name("email") Often good
Dynamic Class By.className("css-82jd8") Potentially unstable
Absolute XPath /html/body/div[1]/div[2]/button Usually fragile

 


 

 

29. DOM and StaleElementReferenceException

 

 

A stale element exception can occur when Selenium holds a reference to an element that is no longer attached to the current DOM.

 

 

For example, a page may replace an existing element after an AJAX update. The old WebElement reference may no longer represent the current element.

 

 


 

 

30. Handling Stale Elements

 

 

A common strategy is to locate the element again after the DOM has changed.

 

 

WebElement button = driver.findElement(By.id("login"));

 


button.click();



WebElement refreshedButton = driver.findElement(By.id("login"));


refreshedButton.click();

 

 

In real automation frameworks, explicit waits and controlled retry strategies can also be used where appropriate.

 

 


 

 

31. DOM and Explicit Wait

 

 

Explicit waits allow Selenium to wait for a specific condition before continuing.

 

 

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

 



WebElement login = wait.until(


    ExpectedConditions.elementToBeClickable(By.id("login"))


);



login.click();

 

 

This is useful when an element exists in the DOM but is not yet ready for interaction.

 

 


 

 

32. Presence vs Visibility

 

 

An element may be present in the DOM without being visible to the user.

 

 

 

 

 

 

 

 

 

 

 

Condition Meaning
Presence Element exists in the DOM.
Visibility Element exists and is displayed to the user.
Clickability Element can generally be interacted with through a click.

 


 

 

33. Hidden Elements

 

 

Webpages may contain elements that exist in the DOM but are hidden using CSS or application logic.

 

 

<button id="submit" style="display:none">Submit</button>

 

 

The element exists in the DOM, but it is not visible.

 

 

Selenium interaction should normally target elements that are available for the intended user interaction.

 

 


 

 

34. DOM and Forms

 

 

Forms contain multiple elements such as text boxes, radio buttons, checkboxes, dropdowns, and submit buttons.

 

 

<form id="registration">

 


    <input id="name" type="text">


    <input id="email" type="email">


    <input id="terms" type="checkbox">


    <button type="submit">Register</button>


</form>

 

 

Selenium can locate each element and automate the complete form workflow.

 

 


 

 

35. DOM and Tables

 

 

HTML tables have a hierarchical DOM structure containing table, row, header, and cell elements.

 

 

<table>

 


    <tr>


        <th>Name</th>


        <th>Email</th>


    </tr>


    <tr>


        <td>John</td>


        <td>[email protected]</td>


    </tr>


</table>

 

 

Understanding the hierarchy makes it easier to create XPath expressions for specific rows and cells.

 

 


 

 

36. DOM and Navigation Menus

 

 

Navigation menus are commonly represented by nested lists, links, buttons, and containers.

 

 

<nav>

 


    <ul>


        <li><a href="/home">Home</a></li>


        <li><a href="/about">About</a></li>


        <li><a href="/contact">Contact</a></li>


    </ul>


</nav>

 

 


 

 

37. DOM and Modals

 

 

Modals can be dynamically inserted into the DOM after a button is clicked.

 

 

Click Login

 


     ↓


JavaScript executes


     ↓


Modal is inserted into DOM


     ↓


Selenium locates modal


     ↓


Selenium enters credentials


     ↓


Selenium submits form

 

 


 

 

38. DOM and Autocomplete Fields

 

 

Autocomplete components frequently create suggestion elements dynamically.

 

 

User enters "Ind"

 


       ↓


Application sends request


       ↓


Suggestions returned


       ↓


DOM updated


       ↓


Suggestion list appears


       ↓


Selenium selects required option

 

 

Because the suggestions may not exist initially, synchronization is important.

 

 


 

 

39. DOM and Nested Elements

 

 

Complex applications often contain deeply nested elements.

 

 

<div class="page">

 


    <div class="content">


        <section class="login">


            <form>


                <div class="field">


                    <input id="username">


                </div>


            </form>


        </section>


    </div>


</div>

 

 

Understanding the hierarchy helps testers construct meaningful XPath and CSS selectors.

 

 


 

 

40. XPath Parent Relationship

 

 

XPath can navigate from an element to its parent.

 

 

//input[@id='username']/parent::div

 

 

This expression identifies the parent div of the username input.

 

 


 

 

41. XPath Child Relationship

 

 

//div[@class='login']/child::button

 

 

This identifies button elements that are direct children of the specified div.

 

 


 

 

42. XPath Descendant Relationship

 

 

//div[@class='login']//button

 

 

The double slash allows navigation to descendant buttons at different levels below the specified div.

 

 


 

 

43. XPath Ancestor Relationship

 

 

//input[@id='username']/ancestor::form

 

 

This can be used to locate an ancestor form containing the username field.

 

 


 

 

44. XPath Following-Sibling

 

 

//label[text()='Username']/following-sibling::input

 

 

This can locate an input element that follows a label within the same parent context.

 

 


 

 

45. XPath Preceding-Sibling

 

 

//input[@id='username']/preceding-sibling::label

 

 

This identifies a label that appears before the username input within the relevant sibling relationship.

 

 


 

 

46. Text-Based XPath

 

 

Visible text can sometimes be used to locate elements.

 

 

//button[text()='Login']

 

 

For partially matching text:

 

 

//button[contains(text(),'Login')]

 

 

Text-based locators should be used carefully when text may change due to localization, content updates, or UI redesign.

 

 


 

 

47. DOM and Data Attributes

 

 

Modern applications may provide custom data attributes specifically for identifying elements.

 

 

<button data-testid="login-button">Login</button>

 

 

A CSS selector can locate this element:

 

 

[data-testid='login-button']

 

 

When such attributes are intentionally designed to remain stable, they can be useful for automation.

 

 


 

 

48. DOM and Accessibility Attributes

 

 

Accessibility-related attributes can also provide useful information about an element.

 

 

<button aria-label="Submit Login">Login</button>

 

 

Such attributes can sometimes be used as locator information when they are stable and appropriate for the application.

 

 


 

 

49. DOM and Shadow DOM

 

 

Shadow DOM is a web platform feature used to encapsulate a component's internal DOM structure.

 

 

Applications and component libraries may use Shadow DOM to isolate internal markup and styles.

 

 


 

 

50. Regular DOM vs Shadow DOM

 

 

 

 

 

 

 

 

 

 

 

Regular DOM Shadow DOM
Part of the normal document tree. Encapsulated DOM structure.
Usually directly accessible through standard DOM traversal. May require entering the appropriate shadow root.
Commonly inspected directly in Developer Tools. Displayed as a shadow tree in supported browsers.

 


 

 

51. Open Shadow DOM

 

 

An open Shadow DOM allows scripts and automation tools to access the shadow root through supported browser APIs.

 

 

WebElement host = driver.findElement(By.cssSelector("my-component"));

 


SearchContext shadowRoot = host.getShadowRoot();


WebElement button = shadowRoot.findElement(By.cssSelector("button"));


button.click();

 

 


 

 

52. DOM and Iframes

 

 

An iframe contains another browsing context. Selenium must switch into the appropriate frame before interacting with elements inside it.

 

 

driver.switchTo().frame("paymentFrame");

 


driver.findElement(By.id("cardNumber")).sendKeys("1234");


driver.switchTo().defaultContent();

 

 

The important concept is that DOM structure and browsing context are related but not identical. An element inside an iframe belongs to that frame's document context.

 

 


 

 

53. DOM Context vs Frame Context

 

 

If an element appears inside an iframe, simply creating an XPath based on the visible page is not enough. Selenium must first switch to the iframe's browsing context.

 

 

Main Page

 


   |


   └── iframe


       |


       └── Frame Document


           |


           └── Input Element

 

 


 

 

54. DOM and Multiple Windows

 

 

Multiple browser windows or tabs have separate browsing contexts. Selenium must switch to the required window before locating elements within it.

 

 

String originalWindow = driver.getWindowHandle();

 



for (String window : driver.getWindowHandles()) {


    if (!window.equals(originalWindow)) {


        driver.switchTo().window(window);


        break;


    }


}

 

 


 

 

55. DOM Debugging Workflow

 

 

When Selenium cannot locate an element, inspect the DOM systematically.

 

 

 

 

  1. Open Developer Tools.

 

 

  1. Inspect the required element.

 

 

  1. Verify whether the element exists.

 

 

  1. Check its ID, class, name, and other attributes.

 

 

  1. Check whether the element is inside an iframe.

 

 

  1. Check whether it is inside Shadow DOM.

 

 

  1. Check whether the element is dynamically generated.

 

 

  1. Verify the XPath or CSS selector.

 

 

  1. Check synchronization requirements.

 

 

  1. Retry the automation after correcting the issue.

 

 

 

 


 

 

56. Common Selenium Exceptions Related to DOM

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Exception Possible DOM-Related Cause
NoSuchElementException Element cannot be found using the supplied locator or current context.
StaleElementReferenceException Previously located element is no longer attached to the current DOM.
ElementNotInteractableException Element exists but cannot currently be interacted with.
ElementClickInterceptedException Another element may be covering the target element.
TimeoutException Expected condition was not satisfied within the specified time.

 


 

 

57. DOM and Page Object Model

 

 

The Page Object Model, or POM, organizes page-specific locators and actions into dedicated classes.

 

 

public class LoginPage {

 


    private WebDriver driver;



    private By username = By.id("username");


    private By password = By.id("password");


    private By loginButton = By.id("login");



    public LoginPage(WebDriver driver) {


        this.driver = driver;


    }



    public void login(String user, String pass) {


        driver.findElement(username).sendKeys(user);


        driver.findElement(password).sendKeys(pass);


        driver.findElement(loginButton).click();


    }


}

 

 

Understanding the DOM helps testers select suitable locators when designing page objects.

 

 


 

 

58. DOM and Test Maintenance

 

 

Web applications change frequently. DOM structures can change because of redesigns, framework upgrades, new components, or backend changes.

 

 

Automation scripts should therefore use maintainable locators rather than depending heavily on fragile DOM paths.

 

 


 

 

59. Absolute XPath

 

 

Absolute XPath starts from the root of the document.

 

 

/html/body/div[1]/div[2]/form/input[1]

 

 

Absolute XPath can become fragile when the page structure changes.

 

 


 

 

60. Relative XPath

 

 

Relative XPath starts from a relevant element or condition rather than depending on the entire document hierarchy.

 

 

//input[@id='username']

 

 

Relative XPath is generally easier to maintain when it is based on stable attributes or meaningful relationships.

 

 


 

 

61. Locator Selection Strategy

 

 

Start

 


  ↓


Inspect DOM


  ↓


Look for stable unique ID


  ↓


If unavailable, check stable data attribute


  ↓


Check name or other stable attribute


  ↓


Consider CSS selector


  ↓


Consider relative XPath


  ↓


Use relationships when necessary


  ↓


Validate locator in Developer Tools

 

 


 

 

62. Real-Time Example: Login Page

 

 

<form id="loginForm">

 


    <input id="username" name="username" type="text">


    <input id="password" name="password" type="password">


    <button id="login" type="submit">Login</button>


</form>

 

 

Selenium automation:

 

 

driver.findElement(By.id("username")).sendKeys("admin");

 


driver.findElement(By.id("password")).sendKeys("admin123");


driver.findElement(By.id("login")).click();

 

 


 

 

63. Real-Time Example: E-Commerce Application

 

 

Consider an e-commerce page containing product cards.

 

 

<div class="product-card">

 


    <h2>Laptop</h2>


    <span class="price">50000</span>


    <button class="add-cart">Add to Cart</button>


</div>

 

 

The DOM structure allows Selenium to identify the product name, price, and Add to Cart button.

 

 


 

 

64. Real-Time Example: Registration Form

 

 

<form id="registration">

 


    <input id="name">


    <input id="email">


    <input id="password">


    <input id="confirmPassword">


    <button id="register">Register</button>


</form>

 

 

Testers can inspect this DOM structure and create locators for each field before automating the registration workflow.

 

 


 

 

65. Real-Time Example: Search Application

 

 

<input id="search" placeholder="Search products">

 


<div id="suggestions">


    <div class="suggestion">Laptop</div>


    <div class="suggestion">Laptop Bag</div>


</div>

 

 

The suggestion elements may be created dynamically after the user enters text. Selenium should wait for the required suggestion to become available before interacting with it.

 

 


 

 

66. DOM and Dynamic Product Cards

 

 

Modern e-commerce applications may dynamically add product cards to the DOM as the user scrolls, searches, filters, or changes categories.

 

 

Automation should account for these dynamic changes using appropriate locators and synchronization.

 

 


 

 

67. DOM and Browser Console

 

 

Browser Developer Tools provide a Console where testers can test JavaScript expressions against the current page.

 

 

document.getElementById("login")

 

 

This can help verify whether an element exists in the current DOM.

 

 


 

 

68. Testing XPath in Browser Developer Tools

 

 

Chrome DevTools can be used to test XPath expressions using JavaScript.

 

 

$x("//button[@id='login']")

 

 

If the XPath matches an element, the result can be inspected directly in Developer Tools.

 

 


 

 

69. Testing CSS Selectors in Browser Developer Tools

 

 

The document.querySelector() method can be used to test a CSS selector.

 

 

document.querySelector("#login")

 

 

For multiple matching elements:

 

 

document.querySelectorAll("button")

 

 


 

 

70. DOM Mutation

 

 

DOM mutation occurs when JavaScript modifies the structure or properties of the document.

 

 

Examples include:

 

 

 

 

  • Adding an element.

 

 

  • Removing an element.

 

 

  • Changing text.

 

 

  • Changing attributes.

 

 

  • Changing classes.

 

 

  • Replacing components.

 

 

  • Updating form controls.

 

 

 

 


 

 

71. DOM and JavaScript

 

 

JavaScript can access and modify DOM elements.

 

 

document.getElementById("message").textContent = "Login successful";

 

 

After this operation, the DOM content changes without necessarily requiring a complete page reload.

 

 


 

 

72. DOM and getText()

 

 

Selenium's getText() method retrieves the visible text associated with an element.

 

 

WebElement message = driver.findElement(By.id("message"));

 


String text = message.getText();


System.out.println(text);

 

 


 

 

73. DOM and getAttribute()

 

 

The getAttribute() method can retrieve an attribute or property value associated with an element.

 

 

String value = driver.findElement(By.id("username"))

 


                     .getAttribute("value");

 

 


 

 

74. DOM Properties vs Attributes

 

 

HTML attributes and DOM properties are related but are not always identical. An HTML attribute is defined in the markup, while a DOM property represents a value maintained by the browser's element object.

 

 

<input id="username" value="admin">

 

 

The current value of an input may change after user interaction even though the original HTML attribute remains unchanged.

 

 


 

 

75. DOM and getDomAttribute()

 

 

Modern Selenium APIs also provide methods for retrieving DOM attribute values more specifically. This distinction can be useful when testers need to understand whether they are reading the element's HTML attribute or its current DOM property value.

 

 


 

 

76. DOM and Visibility Checks

 

 

Before interacting with an element, Selenium testers should understand whether the element is present and visible.

 

 

WebElement element = driver.findElement(By.id("login"));

 



if (element.isDisplayed()) {


    element.click();


}

 

 


 

 

77. DOM and Clickability

 

 

An element can exist in the DOM while another element, overlay, modal, or animation prevents the intended interaction.

 

 

For reliable automation, testers should synchronize with the UI state instead of relying only on the existence of the DOM element.

 

 


 

 

78. DOM and Overlays

 

 

Overlays can temporarily cover buttons or other elements.

 

 

Page

 


 |


 ├── Login Button


 |


 └── Loading Overlay


       ↓


   Covers Button

 

 

In such cases, Selenium may locate the button but the click can still fail because another element intercepts the interaction.

 

 


 

 

79. DOM and Animations

 

 

CSS animations and JavaScript transitions can temporarily change an element's position, visibility, or interactability.

 

 

Explicit synchronization can help automation wait for the expected UI state.

 

 


 

 

80. Common DOM-Related Selenium Mistakes

 

 

 

 

  • Using fragile absolute XPath.

 

 

  • Ignoring dynamic DOM changes.

 

 

  • Using unstable generated class names.

 

 

  • Not checking whether an element is inside an iframe.

 

 

  • Ignoring Shadow DOM.

 

 

  • Using an old WebElement after the DOM has changed.

 

 

  • Not using appropriate waits.

 

 

  • Assuming presence means visibility.

 

 

  • Ignoring overlays and animations.

 

 

  • Creating overly complicated XPath expressions.

 

 

 

 


 

 

81. Best Practices for Selenium Testers

 

 

 

 

  • Understand the DOM before creating locators.

 

 

  • Prefer stable and meaningful attributes.

 

 

  • Use unique IDs when they are stable.

 

 

  • Use data attributes designed for automation when available.

 

 

  • Prefer maintainable CSS selectors or relative XPath.

 

 

  • Avoid unnecessary absolute XPath.

 

 

  • Understand parent-child relationships.

 

 

  • Use explicit waits for dynamic interfaces.

 

 

  • Re-locate elements when the DOM is refreshed or replaced.

 

 

  • Keep locators centralized in Page Object classes.

 

 

  • Validate locators using Developer Tools.

 

 

 

 


 

 

82. DOM Testing Checklist

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Check Question
Element Does the element exist in the current DOM?
Locator Is the locator unique and stable?
Visibility Is the element visible?
Context Is the element inside an iframe?
Shadow DOM Does the element belong to a shadow tree?
Dynamic State Can JavaScript replace or update the element?
Synchronization Does the automation need to wait?
Overlay Is another element covering the target?

 


 

 

83. Practical DOM Exercise

 

 

Create a simple login page and inspect its DOM using Developer Tools.

 

 

<html>

 


<body>


    <div id="login-container">


        <h1>Login</h1>


        <input id="username" type="text" placeholder="Username">


        <input id="password" type="password" placeholder="Password">


        <button id="login">Login</button>


    </div>


</body>


</html>

 

 

Practice the following:

 

 

 

 

  1. Identify the DOM root.

 

 

  1. Identify the parent of the username input.

 

 

  1. Identify the sibling elements.

 

 

  1. Create an ID locator for username.

 

 

  1. Create an ID locator for password.

 

 

  1. Create a CSS selector for the login button.

 

 

  1. Create an XPath for the login button.

 

 

  1. Inspect the element using Developer Tools.

 

 

  1. Test the locator in the browser.

 

 

  1. Automate the login workflow using Selenium.

 

 

 

 


 

 

84. Complete DOM Workflow for Selenium

 

 

HTML Source

 


    ↓


Browser Parses HTML


    ↓


DOM Tree Created


    ↓


JavaScript May Modify DOM


    ↓


Developer Tools Shows Current DOM


    ↓


Tester Inspects Element


    ↓


Tester Identifies Stable Attributes


    ↓


Tester Creates XPath/CSS Locator


    ↓


Selenium Searches Current Context


    ↓


WebElement Returned


    ↓


Wait for Required State


    ↓


Perform Action


    ↓


Validate Result

 

 


 

 

85. DOM and Automation Framework Design

 

 

Understanding the DOM is not limited to writing individual Selenium scripts. It also influences automation framework design.

 

 

A good framework should separate page locators, page actions, test logic, test data, configuration, reporting, and reusable utilities.

 

 

Automation Framework

 


├── Tests


├── Pages


│   ├── LoginPage


│   ├── HomePage


│   └── ProductPage


├── Utilities


├── Test Data


├── Configuration


└── Reports

 

 


 

 

86. DOM and Page Object Repository

 

 

Locators can be stored inside page classes or a dedicated repository. This reduces duplication and makes maintenance easier when the DOM changes.

 

 

private By username = By.id("username");

 


private By password = By.id("password");


private By loginButton = By.id("login");

 

 


 

 

87. DOM and Automation Debugging

 

 

When a test fails, the DOM can provide valuable debugging information.

 

 

A tester should check:

 

 

 

 

  • Whether the element still exists.

 

 

  • Whether its ID or class changed.

 

 

  • Whether the element moved to another container.

 

 

  • Whether the element is inside an iframe.

 

 

  • Whether a new DOM element replaced the old one.

 

 

  • Whether an overlay is blocking interaction.

 

 

  • Whether synchronization is required.

 

 

 

 


 

 

88. DOM and Test Automation Strategy

 

 

A strong Selenium automation strategy considers the application's DOM structure while avoiding excessive dependence on implementation details.

 

 

The objective is to create automation that remains reliable even when minor UI changes occur.

 

 


 

 

89. Interview Questions

 

 

Q1. What is DOM?

 

 

DOM stands for Document Object Model. It represents an HTML document as a hierarchical tree of nodes and objects.

 

 

Q2. Why is DOM important in Selenium?

 

 

Selenium interacts with web elements represented within the browser's document structure. Understanding the DOM helps testers inspect elements and create reliable locators.

 

 

Q3. What is a DOM tree?

 

 

A DOM tree is the hierarchical representation of an HTML document containing relationships between elements, nodes, attributes, and text.

 

 

Q4. What is the difference between HTML and DOM?

 

 

HTML is the markup used to define the document, while the DOM is the browser-created object representation of that document.

 

 

Q5. What is a WebElement?

 

 

WebElement is Selenium's representation of an element on a webpage that allows automation scripts to interact with it.

 

 

Q6. Why can a Selenium element become stale?

 

 

An element can become stale when the DOM changes and the previously referenced element is removed or replaced.

 

 

Q7. How can you inspect the DOM?

 

 

Browser Developer Tools can be used to inspect the current DOM, attributes, relationships, and element structure.

 

 

Q8. What is the difference between presence and visibility?

 

 

Presence means the element exists in the DOM. Visibility means the element is displayed and available to the user.

 

 

Q9. What is Shadow DOM?

 

 

Shadow DOM is an encapsulated DOM structure used by web components to isolate internal markup and styles.

 

 

Q10. Why should absolute XPath generally be avoided?

 

 

Absolute XPath depends heavily on the complete DOM hierarchy and can break when the page structure changes.

 

 


 

 

90. Advanced Interview Questions

 

 

Q1. Can an element exist in the DOM but not be visible?

 

 

Yes. CSS properties or application state can make an element present in the DOM while keeping it hidden.

 

 

Q2. What happens when JavaScript modifies the DOM?

 

 

The current DOM can change by adding, removing, replacing, or modifying elements and attributes.

 

 

Q3. Why does StaleElementReferenceException occur?

 

 

It can occur when the WebElement reference points to an element that is no longer attached to the current DOM.

 

 

Q4. How do you handle dynamic DOM elements?

 

 

Use stable locators, appropriate explicit waits, and re-locate elements when necessary after DOM updates.

 

 

Q5. Why is understanding parent-child relationships useful?

 

 

Parent-child relationships help testers construct XPath and CSS selectors for elements that do not have convenient unique attributes.

 

 


 

 

91. Quick DOM Cheat Sheet

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Concept Meaning
DOM Document Object Model
Node Unit in the DOM structure
Element HTML component represented in the DOM
Parent Element containing another element
Child Element contained by another element
Sibling Elements sharing the same parent
Ancestor Element appearing above another element
Descendant Element appearing below another element
Attribute Additional information defined on an element
WebElement Selenium representation of a webpage element
Shadow DOM Encapsulated DOM structure
Iframe Separate browsing context embedded in a page

 


 

 

92. Final DOM Checklist for Selenium Testers

 

 

 

 

  • Understand how browsers create the DOM.

 

 

  • Understand the DOM tree.

 

 

  • Identify elements and attributes.

 

 

  • Understand parent-child relationships.

 

 

  • Understand sibling relationships.

 

 

  • Inspect elements using Developer Tools.

 

 

  • Use stable locators.

 

 

  • Understand XPath.

 

 

  • Understand CSS selectors.

 

 

  • Handle dynamic DOM updates.

 

 

  • Use explicit waits where appropriate.

 

 

  • Understand stale elements.

 

 

  • Understand iframes.

 

 

  • Understand Shadow DOM.

 

 

  • Use Page Object Model for maintainability.

 

 

 

 


 

 

93. Conclusion

 

 

Understanding the DOM is a fundamental skill for Selenium automation testers. The DOM explains how the browser represents HTML elements and how those elements are organized through parent-child, sibling, ancestor, and descendant relationships.

 

 

A strong understanding of the DOM helps testers create better XPath and CSS selectors, inspect web elements, automate dynamic applications, handle iframes and Shadow DOM, troubleshoot Selenium exceptions, and build maintainable automation frameworks.

 

 

For Selenium learners, DOM knowledge provides the foundation for important topics such as locators, WebElements, dynamic elements, waits, Page Object Model, framework development, and real-world web application automation.

 

 


 

 

94. Selenium Training Resource

 

 

To learn more about Selenium automation testing, WebDriver, locators, TestNG, Page Object Model, framework development, and practical automation concepts, visit the JustAcademy Selenium Training Course.

 

 


 

 

95. Course Demo Registration

 

 

For a course demonstration and additional information about Selenium training, visit the JustAcademy Free Course Demo Registration.

 

 


 

 

96. Final Summary

 

 

The DOM is the structured representation of a webpage created by the browser. Selenium uses this structure to locate and interact with web elements. By understanding DOM nodes, elements, attributes, relationships, dynamic updates, XPath, CSS selectors, iframes, Shadow DOM, and synchronization, Selenium testers can build more reliable and maintainable automation scripts.

 

 

 

Previous Next
whatsapp