<div class="selenium-notes">
<h1>Handling Dynamic Elements in Selenium</h1>
<p><strong>JustAcademy Selenium Training:</strong> <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">JustAcademy Selenium Training Course</a></p>
<p><strong>JustAcademy Demo Registration:</strong> <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Selenium Course Demo</a></p>
<p>Handling Dynamic Elements is an important Selenium WebDriver skill because modern web applications frequently create, remove, update, or modify web elements while the application is running. Dynamic elements may change their attributes, text, location, visibility, enabled state, or DOM structure depending on user actions, AJAX responses, API calls, JavaScript execution, page navigation, or application state.</p>
<p>JustAcademy's Selenium curriculum includes handling dynamic elements together with implicit wait, explicit wait, FluentWait, page-load synchronization, and stable test execution strategies. Its related Selenium material also describes dynamic web elements as elements that can change because of user interaction or asynchronous data loading, with waits and advanced locators used to make automation more reliable. <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Selenium Training Course</a> | <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Selenium Course Demo</a></p>
<hr>
<h2>1. What are Dynamic Elements?</h2>
<p>Dynamic elements are web elements whose properties, location, content, availability, or existence can change during application execution. Unlike static elements, their HTML representation may not remain exactly the same between page loads or user interactions.</p>
<pre><code>Static Element
↓
Same ID
Same Class
Same Text
Same Location
↓
Easy to Locate
Dynamic Element
↓
Changing ID
Changing Class
Changing Text
Changing Position
Delayed Appearance
DOM Replacement
↓
Requires Robust Handling</code></pre>
<hr>
<h2>2. Why are Dynamic Elements Difficult in Selenium?</h2>
<p>Selenium interacts with the DOM exposed by the browser. If an element is generated later, replaced after an AJAX request, or receives changing attributes, a locator that worked previously may not work in the same way during another execution.</p>
<p>Common problems include unstable locators, delayed element creation, stale element references, dynamic text, changing attributes, loading overlays, asynchronous requests, dynamic tables, autocomplete suggestions, and components that are re-rendered by modern JavaScript frameworks.</p>
<hr>
<h2>3. Static vs Dynamic Elements</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Static Element</th><th>Dynamic Element</th></tr>
<tr><td>Properties usually remain constant.</td><td>One or more properties can change.</td></tr>
<tr><td>Usually easier to locate.</td><td>May require flexible locators.</td></tr>
<tr><td>Often available immediately.</td><td>May appear after asynchronous processing.</td></tr>
<tr><td>Usually has predictable DOM structure.</td><td>DOM structure may change.</td></tr>
<tr><td>Simple synchronization may be sufficient.</td><td>Synchronization is often required.</td></tr>
</table>
<hr>
<h2>4. Example of a Static Element</h2>
<pre><code><button id="loginButton">
Login
</button></code></pre>
<p>The ID remains the same, so a simple locator can be used.</p>
<pre><code>driver.findElement(
By.id("loginButton")).click();</code></pre>
<hr>
<h2>5. Example of a Dynamic Element</h2>
<pre><code><button id="button_78291">
Login
</button></code></pre>
<p>On another execution, the ID might become:</p>
<pre><code><button id="button_91384">
Login
</button></code></pre>
<p>A locator based on the complete dynamic ID can therefore become unreliable.</p>
<hr>
<h2>6. Common Characteristics of Dynamic Elements</h2>
<ul>
<li>Automatically generated IDs.</li>
<li>Changing class names.</li>
<li>Changing attributes.</li>
<li>Changing text.</li>
<li>Elements created after an AJAX request.</li>
<li>Elements loaded after JavaScript execution.</li>
<li>Elements that appear after a user action.</li>
<li>Elements that disappear after processing.</li>
<li>Elements replaced during DOM re-rendering.</li>
<li>Dynamic tables and rows.</li>
<li>Dynamic dropdown options.</li>
<li>Autocomplete suggestions.</li>
<li>Loading indicators.</li>
<li>Dynamic popups and modals.</li>
<li>Changing button states.</li>
<li>Lazy-loaded content.</li>
</ul>
<hr>
<h2>7. Main Challenges in Handling Dynamic Elements</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Challenge</th><th>Example</th><th>Common Approach</th></tr>
<tr><td>Changing ID</td><td>button_123 to button_456</td><td>Partial attribute locator.</td></tr>
<tr><td>Changing class</td><td>item-active to item-selected</td><td>Stable class or attribute.</td></tr>
<tr><td>Delayed appearance</td><td>Search result appears later.</td><td>Explicit wait.</td></tr>
<tr><td>Dynamic text</td><td>Loading to Completed.</td><td>Text condition.</td></tr>
<tr><td>DOM replacement</td><td>React re-render.</td><td>Re-locate element.</td></tr>
<tr><td>Dynamic rows</td><td>AJAX table.</td><td>Wait for rows.</td></tr>
<tr><td>Dynamic dropdown</td><td>Options loaded after click.</td><td>Wait for option.</td></tr>
<tr><td>Overlay</td><td>Loading spinner.</td><td>Wait for invisibility.</td></tr>
</table>
<hr>
<h2>8. Dynamic IDs</h2>
<p>One of the most common dynamic-element problems is an automatically generated ID.</p>
<pre><code><input id="user_12873" type="text"></code></pre>
<p>The next execution may generate:</p>
<pre><code><input id="user_98432" type="text"></code></pre>
<p>This locator is fragile:</p>
<pre><code>driver.findElement(
By.id("user_12873"));</code></pre>
<hr>
<h2>9. Handling Dynamic IDs with XPath contains()</h2>
<p>If a stable portion of the ID remains constant, XPath <code>contains()</code> can be used.</p>
<pre><code>driver.findElement(
By.xpath("//input[contains(@id,'user_')]"))
.sendKeys("admin");</code></pre>
<p>This works when the changing part is different but the meaningful prefix remains stable.</p>
<hr>
<h2>10. Handling Dynamic IDs with starts-with()</h2>
<pre><code>driver.findElement(
By.xpath("//input[starts-with(@id,'user_')]"))
.sendKeys("admin");</code></pre>
<p><code>starts-with()</code> is useful when a stable prefix is available.</p>
<hr>
<h2>11. Handling Dynamic IDs with CSS Attribute Selectors</h2>
<p>CSS selectors can also identify elements using partial attribute values.</p>
<pre><code>driver.findElement(
By.cssSelector("input[id^='user_']"))
.sendKeys("admin");</code></pre>
<p>The <code>^=</code> CSS operator means that the attribute value starts with the specified text.</p>
<hr>
<h2>12. CSS contains Attribute Selector</h2>
<pre><code>driver.findElement(
By.cssSelector("input[id*='user_']"))
.sendKeys("admin");</code></pre>
<p>The <code>*=</code> operator searches for an attribute value containing the specified text.</p>
<hr>
<h2>13. CSS ends-with Attribute Selector</h2>
<pre><code>driver.findElement(
By.cssSelector("input[id$='_field']"))
.sendKeys("admin");</code></pre>
<p>The <code>$=</code> operator matches an attribute value ending with the specified text.</p>
<hr>
<h2>14. Dynamic Class Names</h2>
<p>Some applications generate changing class names.</p>
<pre><code><button class="btn_x7a91 primary">
Login
</button></code></pre>
<p>Instead of depending on the unstable class, identify a stable attribute or class.</p>
<pre><code>driver.findElement(
By.cssSelector("button.primary"))
.click();</code></pre>
<hr>
<h2>15. Dynamic Text</h2>
<p>Text can also change depending on application state.</p>
<pre><code><div id="status">Loading...</div></code></pre>
<p>Later:</p>
<pre><code><div id="status">Completed</div></code></pre>
<p>Use a stable locator for the element and synchronize with the expected text.</p>
<pre><code>WebDriverWait wait = new WebDriverWait(
driver,
Duration.ofSeconds(10));
wait.until(
ExpectedConditions.textToBePresentInElementLocated(
By.id("status"),
"Completed"));</code></pre>
<hr>
<h2>16. Dynamic Attributes</h2>
<p>Attributes such as <code>class</code>, <code>value</code>, <code>aria-label</code>, <code>data-state</code>, or custom data attributes may change during application execution.</p>
<pre><code><button id="submit" data-state="loading">
Submit
</button></code></pre>
<p>After processing:</p>
<pre><code><button id="submit" data-state="ready">
Submit
</button></code></pre>
<hr>
<h2>17. Waiting for Dynamic Attributes</h2>
<pre><code>wait.until(
ExpectedConditions.attributeToBe(
By.id("submit"),
"data-state",
"ready"));</code></pre>
<hr>
<h2>18. Using attributeContains()</h2>
<pre><code>wait.until(
ExpectedConditions.attributeContains(
By.id("submit"),
"class",
"active"));</code></pre>
<hr>
<h2>19. Dynamic Visibility</h2>
<p>An element may initially exist in the DOM but become visible only after another operation.</p>
<pre><code><div id="result" style="display:none;">
Search Result
</div></code></pre>
<p>After the search:</p>
<pre><code><div id="result">
Search Result
</div></code></pre>
<hr>
<h2>20. Waiting for Dynamic Visibility</h2>
<pre><code>WebElement result = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("result")));</code></pre>
<hr>
<h2>21. Dynamic Element Presence</h2>
<p>Some elements do not exist in the DOM initially and are created later.</p>
<pre><code>wait.until(
ExpectedConditions.presenceOfElementLocated(
By.id("dynamicElement")));</code></pre>
<p>Presence checks that the element exists in the DOM. It should be used when DOM presence is the required condition rather than visual interaction.</p>
<hr>
<h2>22. Presence vs Visibility</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Condition</th><th>Meaning</th><th>Typical Use</th></tr>
<tr><td>Presence</td><td>Element exists in DOM.</td><td>DOM-level availability.</td></tr>
<tr><td>Visibility</td><td>Element is displayed.</td><td>Reading or interacting with visible content.</td></tr>
<tr><td>Clickable</td><td>Element is visible and enabled.</td><td>Click operation.</td></tr>
</table>
<hr>
<h2>23. Dynamic Enabled State</h2>
<p>A button can be visible but disabled until the application completes validation.</p>
<pre><code><button id="submit" disabled>
Submit
</button></code></pre>
<p>After validation:</p>
<pre><code><button id="submit">
Submit
</button></code></pre>
<hr>
<h2>24. Handling Dynamic Enabled Buttons</h2>
<pre><code>wait.until(
ExpectedConditions.elementToBeClickable(
By.id("submit"))).click();</code></pre>
<p>This is generally preferable to checking the button once and immediately clicking it.</p>
<hr>
<h2>25. Dynamic Loading Spinner</h2>
<p>Loading spinners are common in AJAX-based applications.</p>
<pre><code>Search
↓
Spinner Appears
↓
API Request
↓
Response
↓
Results Render
↓
Spinner Disappears</code></pre>
<hr>
<h2>26. Handling Loading Spinner</h2>
<pre><code>driver.findElement(
By.id("search")).click();
wait.until(
ExpectedConditions.invisibilityOfElementLocated(
By.id("loader")));
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("results")));</code></pre>
<hr>
<h2>27. Dynamic AJAX Content</h2>
<p>AJAX allows web applications to communicate with the server without necessarily performing a complete page refresh. Content may therefore appear after Selenium has already continued executing.</p>
<pre><code>Click Load Data
↓
AJAX Request
↓
Server Response
↓
DOM Update
↓
New Element Available</code></pre>
<hr>
<h2>28. Handling AJAX Elements</h2>
<pre><code>driver.findElement(
By.id("loadData")).click();
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("ajaxResult")));</code></pre>
<hr>
<h2>29. Dynamic Dropdowns</h2>
<p>Custom dropdowns frequently load their options dynamically after the dropdown is opened.</p>
<pre><code>driver.findElement(
By.id("countryDropdown")).click();
wait.until(
ExpectedConditions.elementToBeClickable(
By.xpath("//li[normalize-space()='India']")))
.click();</code></pre>
<hr>
<h2>30. Static Select Dropdown vs Dynamic Dropdown</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Static Select</th><th>Dynamic Custom Dropdown</th></tr>
<tr><td>Usually uses HTML select.</td><td>Often uses div, ul, li, buttons, or custom components.</td></tr>
<tr><td>Can be handled with Select.</td><td>Often requires normal element interaction.</td></tr>
<tr><td>Options usually exist in the DOM.</td><td>Options may be generated dynamically.</td></tr>
<tr><td>Synchronization is often simpler.</td><td>May require explicit waits.</td></tr>
</table>
<hr>
<h2>31. Dynamic Autocomplete</h2>
<p>Autocomplete controls typically send a request after the user types a few characters and then display suggestions.</p>
<pre><code>driver.findElement(
By.id("city")).sendKeys("Mum");
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.xpath("//li[contains(.,'Mumbai')]"))).click();</code></pre>
<hr>
<h2>32. Handling Dynamic Search Suggestions</h2>
<pre><code>WebElement search = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("search")));
search.sendKeys("Selenium");
By suggestion = By.xpath(
"//li[contains(normalize-space(.),'Selenium WebDriver')]");
wait.until(
ExpectedConditions.elementToBeClickable(
suggestion)).click();</code></pre>
<hr>
<h2>33. Dynamic Tables</h2>
<p>Dynamic tables may load rows from an API. The number of rows, cell values, pagination, and sorting order may change during runtime.</p>
<pre><code><table id="users">
<tbody>
<tr>
<td>Manish</td>
<td>QA</td>
</tr>
</tbody>
</table></code></pre>
<hr>
<h2>34. Waiting for Dynamic Table Rows</h2>
<pre><code>List<WebElement> rows = wait.until(
ExpectedConditions.visibilityOfAllElementsLocatedBy(
By.cssSelector("#users tbody tr")));</code></pre>
<hr>
<h2>35. Finding a Dynamic Table Row</h2>
<pre><code>By row = By.xpath(
"//table[@id='users']//tr[td[normalize-space()='Manish']]");
wait.until(
ExpectedConditions.visibilityOfElementLocated(
row));</code></pre>
<hr>
<h2>36. Dynamic Pagination</h2>
<p>When pagination is used, clicking the next-page button may trigger an asynchronous update.</p>
<pre><code>wait.until(
ExpectedConditions.elementToBeClickable(
By.id("nextPage"))).click();
wait.until(
ExpectedConditions.visibilityOfAllElementsLocatedBy(
By.cssSelector("table tbody tr")));</code></pre>
<hr>
<h2>37. Dynamic Search Results</h2>
<pre><code>driver.findElement(
By.id("searchBox")).sendKeys("Selenium");
driver.findElement(
By.id("searchButton")).click();
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.cssSelector(".search-result")));</code></pre>
<hr>
<h2>38. Dynamic Modal</h2>
<p>A modal can be created only after the user clicks a button.</p>
<pre><code>driver.findElement(
By.id("openModal")).click();
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("modal")));
wait.until(
ExpectedConditions.elementToBeClickable(
By.id("confirm"))).click();</code></pre>
<hr>
<h2>39. Dynamic Toast Messages</h2>
<p>Toast notifications often appear for only a short period.</p>
<pre><code>driver.findElement(
By.id("save")).click();
String message = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.cssSelector(".toast")))
.getText();
System.out.println(message);</code></pre>
<hr>
<h2>40. Waiting for Toast Text</h2>
<pre><code>wait.until(
ExpectedConditions.textToBePresentInElementLocated(
By.cssSelector(".toast"),
"Saved successfully"));</code></pre>
<hr>
<h2>41. Dynamic Checkboxes</h2>
<p>A checkbox can be dynamically generated or its selection state can change after another operation.</p>
<pre><code>By checkbox = By.id("terms");
wait.until(
ExpectedConditions.elementToBeClickable(
checkbox)).click();
wait.until(
ExpectedConditions.elementToBeSelected(
checkbox));</code></pre>
<hr>
<h2>42. Dynamic Radio Buttons</h2>
<pre><code>By radio = By.id("premium");
wait.until(
ExpectedConditions.elementToBeClickable(
radio)).click();
wait.until(
ExpectedConditions.elementToBeSelected(
radio));</code></pre>
<hr>
<h2>43. Dynamic File Upload Control</h2>
<p>When the file input is present dynamically, wait for the input before using <code>sendKeys()</code>.</p>
<pre><code>By fileInput = By.cssSelector(
"input[type='file']");
wait.until(
ExpectedConditions.presenceOfElementLocated(
fileInput))
.sendKeys("C:\\files\\document.pdf");</code></pre>
<hr>
<h2>44. Dynamic Iframes</h2>
<p>An iframe may become available only after the application finishes loading or after a user action.</p>
<pre><code>wait.until(
ExpectedConditions.frameToBeAvailableAndSwitchToIt(
By.id("paymentFrame")));
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("cardNumber")));</code></pre>
<hr>
<h2>45. Dynamic Alerts</h2>
<p>JavaScript alerts may appear after asynchronous processing.</p>
<pre><code>driver.findElement(
By.id("delete")).click();
Alert alert = wait.until(
ExpectedConditions.alertIsPresent());
alert.accept();</code></pre>
<hr>
<h2>46. Dynamic Windows and Tabs</h2>
<p>A new tab or window can be opened after an action and may not be immediately available.</p>
<pre><code>String parent = driver.getWindowHandle();
driver.findElement(
By.id("openWindow")).click();
wait.until(
ExpectedConditions.numberOfWindowsToBe(2));
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(parent)) {
driver.switchTo().window(handle);
break;
}
}</code></pre>
<hr>
<h2>47. Dynamic URLs</h2>
<p>After an action, an application may navigate asynchronously to a URL containing dynamic path or query parameters.</p>
<pre><code>driver.findElement(
By.id("profile")).click();
wait.until(
ExpectedConditions.urlContains(
"/profile"));</code></pre>
<hr>
<h2>48. Dynamic Page Titles</h2>
<pre><code>wait.until(
ExpectedConditions.titleContains(
"Dashboard"));</code></pre>
<hr>
<h2>49. Dynamic React Components</h2>
<p>React applications can re-render components when their state or props change. A WebElement reference captured before the re-render can become stale.</p>
<pre><code>By button = By.id("dynamicButton");
driver.findElement(
By.id("update")).click();
wait.until(
ExpectedConditions.elementToBeClickable(
button)).click();</code></pre>
<hr>
<h2>50. Dynamic Angular Components</h2>
<p>Angular applications can update component content after asynchronous operations and state changes.</p>
<pre><code>driver.findElement(
By.id("load")).click();
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("angularResult")));</code></pre>
<hr>
<h2>51. Dynamic Vue Components</h2>
<p>Vue applications use reactive updates that can change DOM content during runtime.</p>
<pre><code>driver.findElement(
By.id("load")).click();
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.cssSelector("[data-testid='result']")));</code></pre>
<hr>
<h2>52. StaleElementReferenceException</h2>
<p>One of the most important problems with dynamic elements is <code>StaleElementReferenceException</code>. It occurs when the previously located element is no longer attached to the current DOM.</p>
<pre><code>WebElement element = driver.findElement(
By.id("result"));
driver.findElement(
By.id("refresh")).click();
element.click();</code></pre>
<p>The refresh or re-render can replace the original DOM node.</p>
<hr>
<h2>53. Handling Stale Elements</h2>
<p>Instead of storing an old WebElement and using it after a DOM update, store the locator and locate the current element again.</p>
<pre><code>By result = By.id("result");
driver.findElement(
By.id("refresh")).click();
wait.until(
ExpectedConditions.elementToBeClickable(
result)).click();</code></pre>
<hr>
<h2>54. Waiting for Staleness</h2>
<pre><code>WebElement oldElement = driver.findElement(
By.id("result"));
driver.findElement(
By.id("refresh")).click();
wait.until(
ExpectedConditions.stalenessOf(
oldElement));</code></pre>
<hr>
<h2>55. Dynamic Element with Changing Position</h2>
<p>Elements can move because of sorting, filtering, responsive layouts, animations, or dynamically inserted content. Avoid relying on screen coordinates as a primary locator.</p>
<pre><code>Wrong approach:
Click at fixed screen coordinate
Better approach:
Locate the element using stable DOM attributes
and synchronize with its required state.</code></pre>
<hr>
<h2>56. Dynamic Elements with Changing Text</h2>
<p>If only part of the text is stable, use a partial text strategy.</p>
<pre><code>driver.findElement(
By.xpath("//button[contains(normalize-space(.),'Order')]"))
.click();</code></pre>
<hr>
<h2>57. normalize-space() for Dynamic Text</h2>
<p><code>normalize-space()</code> is useful when whitespace around the text is inconsistent.</p>
<pre><code>driver.findElement(
By.xpath(
"//button[normalize-space()='Submit Order']"))
.click();</code></pre>
<hr>
<h2>58. Combining Dynamic XPath Conditions</h2>
<p>Multiple stable conditions can make a locator more reliable.</p>
<pre><code>driver.findElement(
By.xpath(
"//button[contains(@class,'primary') and contains(normalize-space(.),'Submit')]"))
.click();</code></pre>
<hr>
<h2>59. Parent-Child Relationship for Dynamic Elements</h2>
<p>When several similar elements exist, locate a stable parent first and then identify the required child.</p>
<pre><code>driver.findElement(
By.xpath(
"//div[@data-product='selenium']//button[contains(.,'Add to Cart')]"))
.click();</code></pre>
<hr>
<h2>60. Descendant Strategy</h2>
<pre><code>driver.findElement(
By.xpath(
"//div[@id='productCard']//button"))
.click();</code></pre>
<p>This can be useful when the child element has unstable attributes but its parent has a stable identifier.</p>
<hr>
<h2>61. Dynamic E-Commerce Product Cards</h2>
<pre><code><div class="product-card" data-product-id="101">
<h3>Selenium Course</h3>
<button>Add to Cart</button>
</div></code></pre>
<pre><code>driver.findElement(
By.xpath(
"//div[@data-product-id='101']//button[normalize-space()='Add to Cart']"))
.click();</code></pre>
<hr>
<h2>62. Dynamic Login Example</h2>
<pre><code>WebDriverWait wait = new WebDriverWait(
driver,
Duration.ofSeconds(10));
By username = By.id("username");
By password = By.id("password");
By login = By.id("login");
By dashboard = By.id("dashboard");
wait.until(
ExpectedConditions.visibilityOfElementLocated(
username)).sendKeys("admin");
wait.until(
ExpectedConditions.visibilityOfElementLocated(
password)).sendKeys("admin123");
wait.until(
ExpectedConditions.elementToBeClickable(
login)).click();
wait.until(
ExpectedConditions.visibilityOfElementLocated(
dashboard));</code></pre>
<hr>
<h2>63. Dynamic Search Example</h2>
<pre><code>By searchBox = By.id("search");
By searchButton = By.id("searchButton");
By result = By.cssSelector(".search-result");
wait.until(
ExpectedConditions.visibilityOfElementLocated(
searchBox)).sendKeys("Selenium");
wait.until(
ExpectedConditions.elementToBeClickable(
searchButton)).click();
wait.until(
ExpectedConditions.visibilityOfElementLocated(
result));</code></pre>
<hr>
<h2>64. Dynamic Registration Example</h2>
<pre><code>By username = By.id("username");
By email = By.id("email");
By password = By.id("password");
By register = By.id("register");
By success = By.id("successMessage");
wait.until(
ExpectedConditions.visibilityOfElementLocated(
username)).sendKeys("testuser");
wait.until(
ExpectedConditions.visibilityOfElementLocated(
email)).sendKeys("[email protected]");
wait.until(
ExpectedConditions.visibilityOfElementLocated(
password)).sendKeys("Password123");
wait.until(
ExpectedConditions.elementToBeClickable(
register)).click();
wait.until(
ExpectedConditions.visibilityOfElementLocated(
success));</code></pre>
<hr>
<h2>65. Dynamic E-Commerce Cart Example</h2>
<pre><code>By addToCart = By.xpath(
"//div[@data-product='101']//button[contains(.,'Add to Cart')]");
By cart = By.id("cart");
By checkout = By.id("checkout");
wait.until(
ExpectedConditions.elementToBeClickable(
addToCart)).click();
wait.until(
ExpectedConditions.visibilityOfElementLocated(
cart));
wait.until(
ExpectedConditions.elementToBeClickable(
checkout)).click();</code></pre>
<hr>
<h2>66. Dynamic Table Example</h2>
<pre><code>By tableRows = By.cssSelector(
"#users tbody tr");
List<WebElement> rows = wait.until(
ExpectedConditions.visibilityOfAllElementsLocatedBy(
tableRows));
for (WebElement row : rows) {
System.out.println(row.getText());
}</code></pre>
<hr>
<h2>67. Dynamic Table Row by Text</h2>
<pre><code>By userRow = By.xpath(
"//table[@id='users']//tr[td[normalize-space()='Manish']]");
WebElement row = wait.until(
ExpectedConditions.visibilityOfElementLocated(
userRow));
System.out.println(row.getText());</code></pre>
<hr>
<h2>68. Dynamic Loading Flow</h2>
<pre><code>Test Starts
↓
Page Loads
↓
Dynamic Component Created
↓
API Request
↓
Loader Displayed
↓
Response Received
↓
DOM Updated
↓
Loader Hidden
↓
Element Becomes Interactive
↓
Selenium Performs Action</code></pre>
<hr>
<h2>69. Implicit Wait for Dynamic Elements</h2>
<p>Implicit Wait tells WebDriver how long to wait when locating elements before reporting that the lookup failed. It is a general lookup mechanism rather than a replacement for condition-specific synchronization.</p>
<pre><code>driver.manage().timeouts().implicitlyWait(
Duration.ofSeconds(10));</code></pre>
<hr>
<h2>70. Explicit Wait for Dynamic Elements</h2>
<p>Explicit Wait is generally more suitable when the test needs to wait for a particular state of a dynamic element.</p>
<pre><code>WebDriverWait wait = new WebDriverWait(
driver,
Duration.ofSeconds(10));
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("dynamicElement")));</code></pre>
<hr>
<h2>71. FluentWait for Dynamic Elements</h2>
<p>FluentWait allows timeout and polling behavior to be configured for a wait.</p>
<pre><code>Wait<WebDriver> fluentWait =
new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(15))
.pollingEvery(Duration.ofMillis(500))
.ignoring(NoSuchElementException.class);
WebElement element = fluentWait.until(
driver -> driver.findElement(
By.id("dynamicElement")));</code></pre>
<hr>
<h2>72. Polling Concept</h2>
<pre><code>Wait Starts
↓
Check Condition
↓
Condition False
↓
Wait for Polling Interval
↓
Check Again
↓
Condition True?
├── Yes → Continue
└── No → Repeat Until Timeout</code></pre>
<hr>
<h2>73. Handling Dynamic Elements with WebDriverWait</h2>
<pre><code>public class DynamicElementHelper {
private WebDriver driver;
private WebDriverWait wait;
public DynamicElementHelper(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(
driver,
Duration.ofSeconds(10));
}
public WebElement waitForVisible(By locator) {
return wait.until(
ExpectedConditions.visibilityOfElementLocated(
locator));
}
public WebElement waitForClickable(By locator) {
return wait.until(
ExpectedConditions.elementToBeClickable(
locator));
}
public void waitForInvisible(By locator) {
wait.until(
ExpectedConditions.invisibilityOfElementLocated(
locator));
}
}</code></pre>
<hr>
<h2>74. Handling Dynamic Elements with Page Object Model</h2>
<p>Synchronization can be placed inside Page Object methods so that tests remain clean and reusable.</p>
<pre><code>public class LoginPage {
private WebDriver driver;
private WebDriverWait wait;
private By username = By.id("username");
private By password = By.id("password");
private By login = By.id("login");
private By dashboard = By.id("dashboard");
public LoginPage(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(
driver,
Duration.ofSeconds(10));
}
public void login(String user, String pass) {
wait.until(
ExpectedConditions.visibilityOfElementLocated(
username)).sendKeys(user);
wait.until(
ExpectedConditions.visibilityOfElementLocated(
password)).sendKeys(pass);
wait.until(
ExpectedConditions.elementToBeClickable(
login)).click();
wait.until(
ExpectedConditions.visibilityOfElementLocated(
dashboard));
}
}</code></pre>
<hr>
<h2>75. Why Page Object Model Helps Dynamic Elements</h2>
<ul>
<li>Locators are centralized.</li>
<li>Wait logic can be centralized.</li>
<li>Dynamic-element handling becomes reusable.</li>
<li>Test cases become easier to read.</li>
<li>Locator changes can be made in one location.</li>
<li>Synchronization logic is separated from test scenarios.</li>
</ul>
<hr>
<h2>76. Handling Dynamic Elements with Stable Attributes</h2>
<p>Modern applications sometimes provide attributes specifically useful for automation, such as <code>data-testid</code>, <code>data-test</code>, or other stable identifiers.</p>
<pre><code><button data-testid="login-button">
Login
</button></code></pre>
<pre><code>driver.findElement(
By.cssSelector(
"[data-testid='login-button']"))
.click();</code></pre>
<hr>
<h2>77. Why Stable Test Attributes Are Useful</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Locator</th><th>Typical Stability</th><th>Comment</th></tr>
<tr><td>Stable ID</td><td>High</td><td>Good when intentionally designed for the element.</td></tr>
<tr><td>data-testid</td><td>High</td><td>Useful dedicated test attribute.</td></tr>
<tr><td>Stable name</td><td>High</td><td>Useful for form controls.</td></tr>
<tr><td>Stable CSS</td><td>Medium to High</td><td>Depends on application structure.</td></tr>
<tr><td>Relative XPath</td><td>Medium</td><td>Can be robust when based on stable relationships.</td></tr>
<tr><td>Absolute XPath</td><td>Low</td><td>Fragile when DOM structure changes.</td></tr>
<tr><td>Random generated class</td><td>Low</td><td>Often changes between builds or renders.</td></tr>
</table>
<hr>
<h2>78. Avoid Absolute XPath for Dynamic Elements</h2>
<pre><code>/html/body/div[2]/div[1]/div[3]/button</code></pre>
<p>This XPath depends heavily on the exact DOM hierarchy. If a container is added or removed, the XPath may stop working.</p>
<hr>
<h2>79. Prefer Relative XPath</h2>
<pre><code>//button[@data-testid='login-button']</code></pre>
<p>Relative XPath can focus on stable attributes and relationships instead of the complete document structure.</p>
<hr>
<h2>80. Dynamic Elements and XPath contains()</h2>
<pre><code>//button[contains(@id,'submit_')]</code></pre>
<hr>
<h2>81. Dynamic Elements and XPath starts-with()</h2>
<pre><code>//input[starts-with(@id,'user_')]</code></pre>
<hr>
<h2>82. Dynamic Elements and XPath text()</h2>
<pre><code>//button[text()='Login']</code></pre>
<p>When the text itself is dynamic, partial matching can be more appropriate.</p>
<pre><code>//button[contains(text(),'Login')]</code></pre>
<hr>
<h2>83. Dynamic Elements and normalize-space()</h2>
<pre><code>//button[normalize-space()='Login']</code></pre>
<p>This is useful when extra whitespace may be present in the element's text.</p>
<hr>
<h2>84. Combining XPath Conditions</h2>
<pre><code>//button[
contains(@class,'primary')
and contains(normalize-space(.),'Submit')
]</code></pre>
<p>Combining stable conditions can reduce the chance of selecting the wrong element when several similar elements exist.</p>
<hr>
<h2>85. Dynamic Elements with Parent Relationships</h2>
<pre><code>//div[@data-product='101']//button[contains(.,'Buy')]</code></pre>
<p>This approach identifies the target button in the context of a known product container.</p>
<hr>
<h2>86. Dynamic Elements with Sibling Relationships</h2>
<pre><code>//label[normalize-space()='Email']
/following-sibling::input</code></pre>
<p>Relationships can be useful when the input itself has an unstable attribute but its associated label is stable.</p>
<hr>
<h2>87. Dynamic Elements with Following Relationship</h2>
<pre><code>//span[normalize-space()='Username']
/following::input[1]</code></pre>
<p>Use relationship-based XPath carefully and keep the locator as specific as possible.</p>
<hr>
<h2>88. Dynamic Elements in Forms</h2>
<p>Form elements can become available or enabled after validation.</p>
<pre><code>wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("email")))
.sendKeys("[email protected]");
wait.until(
ExpectedConditions.elementToBeClickable(
By.id("submit"))).click();</code></pre>
<hr>
<h2>89. Dynamic Validation Messages</h2>
<pre><code>driver.findElement(
By.id("email")).sendKeys("invalid");
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.cssSelector(".validation-error")));</code></pre>
<hr>
<h2>90. Dynamic Success Messages</h2>
<pre><code>driver.findElement(
By.id("save")).click();
wait.until(
ExpectedConditions.textToBePresentInElementLocated(
By.cssSelector(".success-message"),
"Saved successfully"));</code></pre>
<hr>
<h2>91. Dynamic Notification Badge</h2>
<p>Notification counts may change after an asynchronous operation.</p>
<pre><code>driver.findElement(
By.id("markAsRead")).click();
wait.until(
ExpectedConditions.attributeToBe(
By.id("notificationBadge"),
"data-count",
"0"));</code></pre>
<hr>
<h2>92. Dynamic Cart Count</h2>
<pre><code>driver.findElement(
By.id("addToCart")).click();
wait.until(
ExpectedConditions.textToBePresentInElementLocated(
By.id("cartCount"),
"1"));</code></pre>
<hr>
<h2>93. Dynamic Price Update</h2>
<p>Product prices can change after selecting quantity, size, color, coupon, shipping method, or other options.</p>
<pre><code>driver.findElement(
By.id("quantity")).sendKeys("2");
wait.until(
ExpectedConditions.textToBePresentInElementLocated(
By.id("totalPrice"),
"2000"));</code></pre>
<hr>
<h2>94. Dynamic Filter Results</h2>
<pre><code>driver.findElement(
By.id("category")).click();
wait.until(
ExpectedConditions.elementToBeClickable(
By.xpath("//option[contains(.,'Laptop')]")))
.click();
wait.until(
ExpectedConditions.visibilityOfAllElementsLocatedBy(
By.cssSelector(".product-card")));</code></pre>
<hr>
<h2>95. Dynamic Sorting</h2>
<pre><code>driver.findElement(
By.id("sort")).click();
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.cssSelector(".sorted-results")));</code></pre>
<hr>
<h2>96. Dynamic Infinite Scroll</h2>
<p>Infinite-scroll applications load additional content as the user reaches the bottom of the page.</p>
<pre><code>JavascriptExecutor js =
(JavascriptExecutor) driver;
js.executeScript(
"window.scrollTo(0, document.body.scrollHeight);");
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.cssSelector(".new-results")));</code></pre>
<hr>
<h2>97. Dynamic Lazy Loading</h2>
<pre><code>By image = By.cssSelector(
"[data-testid='product-image']");
WebElement element = wait.until(
ExpectedConditions.presenceOfElementLocated(
image));
JavascriptExecutor js =
(JavascriptExecutor) driver;
js.executeScript(
"arguments[0].scrollIntoView(true);",
element);
wait.until(
ExpectedConditions.visibilityOfElementLocated(
image));</code></pre>
<hr>
<h2>98. Dynamic Overlay Handling</h2>
<pre><code>By overlay = By.cssSelector(
".loading-overlay");
By button = By.id("continue");
wait.until(
ExpectedConditions.invisibilityOfElementLocated(
overlay));
wait.until(
ExpectedConditions.elementToBeClickable(
button)).click();</code></pre>
<hr>
<h2>99. Dynamic Element Retry Strategy</h2>
<p>When a component can be replaced during a short interaction window, it can be useful to re-locate the element rather than holding a potentially stale reference.</p>
<pre><code>By button = By.id("dynamicButton");
for (int i = 0; i < 3; i++) {
try {
wait.until(
ExpectedConditions.elementToBeClickable(
button)).click();
break;
} catch (StaleElementReferenceException e) {
if (i == 2) {
throw e;
}
}
}</code></pre>
<hr>
<h2>100. Dynamic Element Handling Strategy</h2>
<pre><code>Identify Element
↓
Check Whether Locator Is Stable
↓
Identify Dynamic Property
↓
Select Stable Attribute or Relationship
↓
Determine Required State
↓
Choose Appropriate Wait
↓
Locate Current Element
↓
Perform Action
↓
Validate Result</code></pre>
<hr>
<h2>101. Common Mistake: Using Fixed Sleep Everywhere</h2>
<pre><code>Thread.sleep(5000);
driver.findElement(
By.id("result")).click();</code></pre>
<p>A fixed sleep does not verify that the required condition has actually occurred.</p>
<hr>
<h2>102. Better Approach</h2>
<pre><code>wait.until(
ExpectedConditions.elementToBeClickable(
By.id("result"))).click();</code></pre>
<hr>
<h2>103. Common Mistake: Waiting for the Wrong Element</h2>
<pre><code>wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("header")));
driver.findElement(
By.id("dynamicButton")).click();</code></pre>
<p>The header being visible does not prove that the dynamic button is ready.</p>
<hr>
<h2>104. Better Approach: Wait for the Required Element</h2>
<pre><code>wait.until(
ExpectedConditions.elementToBeClickable(
By.id("dynamicButton"))).click();</code></pre>
<hr>
<h2>105. Common Mistake: Increasing Timeout Without Investigation</h2>
<p>If a dynamic element fails to appear, do not immediately increase the timeout. First verify the locator, frame, window, application state, network behavior, overlay, and whether the expected element should actually exist.</p>
<hr>
<h2>106. Common Mistake: Assuming Presence Means Clickable</h2>
<pre><code>WebElement element = wait.until(
ExpectedConditions.presenceOfElementLocated(
By.id("submit")));
element.click();</code></pre>
<p>Presence alone does not guarantee that the element is displayed and enabled.</p>
<hr>
<h2>107. Better Approach for Click Operations</h2>
<pre><code>wait.until(
ExpectedConditions.elementToBeClickable(
By.id("submit"))).click();</code></pre>
<hr>
<h2>108. Common Mistake: Holding WebElement References Too Long</h2>
<p>Long-lived WebElement references are more vulnerable to becoming stale when the application frequently re-renders its DOM.</p>
<pre><code>WebElement element =
driver.findElement(By.id("dynamic"));
performSeveralOperations();
element.click();</code></pre>
<hr>
<h2>109. Better Approach: Store Locators</h2>
<pre><code>By dynamicElement = By.id("dynamic");
wait.until(
ExpectedConditions.elementToBeClickable(
dynamicElement)).click();</code></pre>
<hr>
<h2>110. Common Mistake: Using Random Dynamic Attributes</h2>
<pre><code>By.id("generated_987654321")</code></pre>
<p>Such locators are likely to fail when the generated value changes.</p>
<hr>
<h2>111. Better Approach: Identify the Stable Portion</h2>
<pre><code>By.xpath(
"//input[starts-with(@id,'generated_')]")</code></pre>
<hr>
<h2>112. Common Mistake: Overusing XPath Indexes</h2>
<pre><code>(//button)[7]</code></pre>
<p>If another button is inserted before the target, the index may point to a different element.</p>
<hr>
<h2>113. Better Approach: Use Meaningful Relationships</h2>
<pre><code>//div[@data-product='101']//button[
normalize-space()='Add to Cart'
]</code></pre>
<hr>
<h2>114. Common Mistake: Ignoring Loading Overlays</h2>
<p>A button may be visible but a transparent or visible overlay can intercept the click.</p>
<pre><code>wait.until(
ExpectedConditions.invisibilityOfElementLocated(
By.cssSelector(".loading-overlay")));
wait.until(
ExpectedConditions.elementToBeClickable(
By.id("submit"))).click();</code></pre>
<hr>
<h2>115. Common Mistake: Ignoring DOM Re-Rendering</h2>
<p>Frameworks such as React, Angular, and Vue can replace DOM nodes during state updates. Reusing an old WebElement after such an update can result in stale-element failures.</p>
<hr>
<h2>116. Common Mistake: Using JavaScript Click as the First Solution</h2>
<pre><code>JavascriptExecutor js =
(JavascriptExecutor) driver;
js.executeScript(
"arguments[0].click();",
element);</code></pre>
<p>JavaScript execution can sometimes bypass normal interaction behavior, but it should not automatically be used to hide synchronization or application-state problems. First make sure the element is in the correct state and that normal WebDriver interaction is appropriate.</p>
<hr>
<h2>117. Debugging Dynamic Element Failures</h2>
<pre><code>Test Failure
↓
Check Exception
↓
Check Locator
↓
Check Element DOM
↓
Check Dynamic Attribute
↓
Check Visibility
↓
Check Enabled State
↓
Check Overlay
↓
Check Frame
↓
Check Window
↓
Check DOM Re-render
↓
Choose Correct Synchronization</code></pre>
<hr>
<h2>118. Dynamic Element Debugging Checklist</h2>
<ul>
<li>Inspect the element in browser DevTools.</li>
<li>Check whether its ID changes.</li>
<li>Check whether its class changes.</li>
<li>Check whether its text changes.</li>
<li>Check whether the element is initially present.</li>
<li>Check whether it appears after an API request.</li>
<li>Check whether a loader blocks it.</li>
<li>Check whether the element is inside an iframe.</li>
<li>Check whether the element is inside another window or tab.</li>
<li>Check whether the DOM is re-rendered.</li>
<li>Check whether the locator selects multiple elements.</li>
<li>Check whether the locator remains stable across executions.</li>
<li>Choose the correct ExpectedCondition.</li>
</ul>
<hr>
<h2>119. Dynamic Element Handling in a Real Test Flow</h2>
<pre><code>Open Application
↓
Wait for Login Form
↓
Enter Credentials
↓
Click Login
↓
Wait for Loader to Disappear
↓
Wait for Dashboard
↓
Search Product
↓
Wait for Suggestions
↓
Select Product
↓
Wait for Product Details
↓
Add Product
↓
Wait for Cart Update
↓
Open Cart
↓
Wait for Checkout
↓
Complete Checkout
↓
Wait for Confirmation
↓
Validate Result</code></pre>
<hr>
<h2>120. Practical Project: Dynamic E-Commerce Application</h2>
<p>A practical dynamic-element automation project can include product search, autocomplete suggestions, product cards, dynamic prices, add-to-cart operations, cart updates, checkout, loading overlays, and order confirmation.</p>
<pre><code>public class EcommerceTest {
WebDriver driver;
WebDriverWait wait;
@Test
public void dynamicElementTest() {
By search = By.id("search");
By suggestion = By.xpath(
"//li[contains(.,'Selenium')]");
By product = By.xpath(
"//div[@data-product='101']//button[contains(.,'Add to Cart')]");
By cart = By.id("cart");
By checkout = By.id("checkout");
By confirmation = By.id("orderConfirmation");
wait.until(
ExpectedConditions.visibilityOfElementLocated(
search)).sendKeys("Selenium");
wait.until(
ExpectedConditions.elementToBeClickable(
suggestion)).click();
wait.until(
ExpectedConditions.elementToBeClickable(
product)).click();
wait.until(
ExpectedConditions.visibilityOfElementLocated(
cart));
wait.until(
ExpectedConditions.elementToBeClickable(
checkout)).click();
wait.until(
ExpectedConditions.visibilityOfElementLocated(
confirmation));
}
}</code></pre>
<hr>
<h2>121. Recommended Dynamic Element Handling Techniques</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Technique</th><th>Purpose</th></tr>
<tr><td>Stable ID</td><td>Locate elements with a consistent identifier.</td></tr>
<tr><td>data-testid</td><td>Use dedicated stable test attributes.</td></tr>
<tr><td>contains()</td><td>Handle partial dynamic attribute values.</td></tr>
<tr><td>starts-with()</td><td>Handle stable attribute prefixes.</td></tr>
<tr><td>normalize-space()</td><td>Handle inconsistent text whitespace.</td></tr>
<tr><td>Parent-child relationship</td><td>Locate elements within a stable container.</td></tr>
<tr><td>Explicit Wait</td><td>Wait for a specific application condition.</td></tr>
<tr><td>FluentWait</td><td>Customize timeout and polling behavior.</td></tr>
<tr><td>Re-location</td><td>Handle DOM replacement and stale references.</td></tr>
<tr><td>Loader synchronization</td><td>Prevent overlays from blocking interactions.</td></tr>
<tr><td>Page Object Model</td><td>Centralize locators and synchronization.</td></tr>
</table>
<hr>
<h2>122. Dynamic Element Handling Best Practices</h2>
<ul>
<li>Prefer stable locators over generated attributes.</li>
<li>Use dedicated test attributes when available.</li>
<li>Use relative XPath instead of fragile absolute XPath.</li>
<li>Use CSS selectors when they provide a clear stable locator.</li>
<li>Wait for the exact state required by the next action.</li>
<li>Use explicit waits for asynchronous UI behavior.</li>
<li>Wait for overlays to disappear before interacting.</li>
<li>Re-locate elements after DOM replacement.</li>
<li>Keep dynamic-element logic inside Page Objects or reusable utilities.</li>
<li>Avoid unnecessary Thread.sleep() calls.</li>
<li>Do not solve every failure by increasing the timeout.</li>
<li>Verify that the locator is correct before diagnosing synchronization.</li>
<li>Keep synchronization logic readable and maintainable.</li>
<li>Use meaningful application states for synchronization.</li>
<li>Validate the final state after important dynamic operations.</li>
</ul>
<hr>
<h2>123. Dynamic Element Handling Do's and Don'ts</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Do</th><th>Don't</th></tr>
<tr><td>Use stable attributes.</td><td>Depend on random generated IDs.</td></tr>
<tr><td>Use explicit waits for dynamic states.</td><td>Use Thread.sleep() everywhere.</td></tr>
<tr><td>Re-locate after DOM replacement.</td><td>Reuse stale WebElement references.</td></tr>
<tr><td>Wait for overlays to disappear.</td><td>Ignore loading layers.</td></tr>
<tr><td>Use meaningful XPath relationships.</td><td>Overuse absolute XPath.</td></tr>
<tr><td>Verify application state.</td><td>Assume element presence means readiness.</td></tr>
<tr><td>Centralize wait utilities.</td><td>Duplicate synchronization logic everywhere.</td></tr>
<tr><td>Investigate failures.</td><td>Increase timeout blindly.</td></tr>
</table>
<hr>
<h2>124. Interview Questions: What is a Dynamic Element?</h2>
<p><strong>Answer:</strong> A dynamic element is a web element whose properties, content, availability, position, or DOM representation can change during application execution.</p>
<hr>
<h2>125. Interview Questions: Why are Dynamic Elements Difficult to Automate?</h2>
<p><strong>Answer:</strong> Their attributes or DOM representation can change, and they may appear only after asynchronous operations. A static locator or immediate Selenium action may therefore become unreliable.</p>
<hr>
<h2>126. Interview Questions: How Do You Handle Dynamic IDs?</h2>
<p><strong>Answer:</strong> Identify the stable portion of the attribute and use a flexible locator such as XPath <code>contains()</code>, XPath <code>starts-with()</code>, or CSS attribute selectors. Prefer a stable dedicated attribute when available.</p>
<hr>
<h2>127. Interview Questions: How Do You Handle Elements Loaded Through AJAX?</h2>
<p><strong>Answer:</strong> Wait for an observable application condition such as the target element becoming visible, a loading indicator disappearing, expected text appearing, or a relevant attribute changing.</p>
<hr>
<h2>128. Interview Questions: How Do You Handle Stale Dynamic Elements?</h2>
<p><strong>Answer:</strong> Re-locate the element after the DOM update rather than continuing to use the old WebElement reference. A wait for the new element state can be used when appropriate.</p>
<hr>
<h2>129. Interview Questions: Which Wait is Commonly Used for Dynamic Elements?</h2>
<p><strong>Answer:</strong> Explicit Wait is commonly used because it allows the test to wait for a specific condition such as presence, visibility, clickability, text, attribute state, alert, frame, or window availability. FluentWait can be used when customized polling behavior is needed.</p>
<hr>
<h2>130. Interview Questions: What is the Difference Between Presence and Visibility?</h2>
<p><strong>Answer:</strong> Presence means the element exists in the DOM, while visibility means the element satisfies WebDriver's displayedness requirements. A present element may still be hidden.</p>
<hr>
<h2>131. Interview Questions: How Do You Handle Dynamic Dropdowns?</h2>
<p><strong>Answer:</strong> Open the dropdown, wait for the required option to become available or clickable, and then select the option using a stable locator.</p>
<hr>
<h2>132. Interview Questions: How Do You Handle Dynamic Tables?</h2>
<p><strong>Answer:</strong> Wait for the table rows or required data to become available and then locate the desired row using stable attributes, cell text, or relationships within the table.</p>
<hr>
<h2>133. Interview Questions: How Do You Handle Dynamic Buttons?</h2>
<p><strong>Answer:</strong> Use a stable locator and wait until the button reaches the required state, commonly with <code>elementToBeClickable()</code> when the action requires the button to be visible and enabled.</p>
<hr>
<h2>134. Interview Questions: Can Thread.sleep() Handle Dynamic Elements?</h2>
<p><strong>Answer:</strong> Thread.sleep() can delay execution, but it is a fixed delay and does not verify whether the dynamic element has reached the required state. Condition-based waits are generally more suitable.</p>
<hr>
<h2>135. Interview Questions: Can XPath Solve All Dynamic Element Problems?</h2>
<p><strong>Answer:</strong> No. XPath can help create flexible locators, but it does not solve timing or synchronization problems. Dynamic-element handling usually requires both a stable locator strategy and appropriate synchronization.</p>
<hr>
<h2>136. Interview Questions: Can Explicit Wait Fix an Incorrect Locator?</h2>
<p><strong>Answer:</strong> No. An explicit wait can handle timing, but it cannot correct a locator that identifies the wrong element or no element at all.</p>
<hr>
<h2>137. Interview Questions: How Do You Handle Dynamic Loading Spinners?</h2>
<p><strong>Answer:</strong> Wait for the spinner or overlay to become invisible and then wait for the required content or control to become available.</p>
<hr>
<h2>138. Interview Questions: How Do You Handle Dynamic Modals?</h2>
<p><strong>Answer:</strong> Trigger the modal, wait for its container to become visible, and then wait for the required modal control to become clickable before interacting with it.</p>
<hr>
<h2>139. Interview Questions: How Do You Handle Dynamic React Components?</h2>
<p><strong>Answer:</strong> Use stable locators, wait for the required state, and re-locate elements after React re-renders the component when necessary to avoid stale references.</p>
<hr>
<h2>140. Interview Questions: How Do You Make Dynamic Element Automation Reliable?</h2>
<p><strong>Answer:</strong> Use stable locators, condition-based synchronization, appropriate wait strategies, re-location after DOM changes, reusable wait utilities, Page Object Model, and meaningful application-state validation.</p>
<hr>
<h2>141. Dynamic Element Handling Checklist</h2>
<ul>
<li>Identify whether the element is actually dynamic.</li>
<li>Inspect the DOM in browser DevTools.</li>
<li>Find stable attributes.</li>
<li>Check whether IDs are generated dynamically.</li>
<li>Check whether classes are generated dynamically.</li>
<li>Check whether text changes.</li>
<li>Check whether the element appears after an AJAX request.</li>
<li>Check whether the element is initially hidden.</li>
<li>Check whether the element becomes enabled later.</li>
<li>Check for loading overlays.</li>
<li>Check whether the DOM is re-rendered.</li>
<li>Use relative XPath where appropriate.</li>
<li>Use CSS selectors where appropriate.</li>
<li>Use contains() or starts-with() for suitable dynamic attributes.</li>
<li>Use normalize-space() for inconsistent text.</li>
<li>Use parent-child relationships for repeated elements.</li>
<li>Use explicit waits for dynamic states.</li>
<li>Use FluentWait when custom polling is required.</li>
<li>Re-locate elements after DOM replacement.</li>
<li>Avoid unnecessary Thread.sleep().</li>
<li>Keep timeout values reasonable.</li>
<li>Centralize synchronization in reusable methods.</li>
<li>Use Page Object Model for maintainability.</li>
<li>Validate the final application state.</li>
</ul>
<hr>
<h2>142. Final Summary</h2>
<p>Handling Dynamic Elements is a fundamental Selenium WebDriver skill for automating modern web applications. Dynamic elements can change their IDs, classes, attributes, text, visibility, enabled state, position, DOM representation, or availability during runtime.</p>
<p>Reliable dynamic-element automation requires two major strategies: <strong>creating stable locators</strong> and <strong>synchronizing with the correct application state</strong>. XPath functions such as <code>contains()</code>, <code>starts-with()</code>, and <code>normalize-space()</code>, CSS attribute selectors, stable test attributes, and parent-child relationships can help locate changing elements.</p>
<p>Synchronization techniques such as explicit waits, FluentWait, visibility checks, clickability checks, text conditions, attribute conditions, staleness checks, frame waits, window waits, and loader synchronization help Selenium interact with elements at the appropriate time.</p>
<p>The most important principle is to avoid treating dynamic-element failures as simple timing problems. First identify the reason the element is dynamic, choose a stable locator, determine the required application state, use the appropriate synchronization condition, and re-locate the element when the DOM has been replaced.</p>
<hr>
<h2>143. Selenium Training Resources</h2>
<p>Learn Selenium WebDriver, Java automation, locators, dynamic elements, waits, synchronization, TestNG, Page Object Model, automation frameworks, and practical automation testing through the <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Selenium Training Course</a>.</p>
<p>For a course demonstration, visit the <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Selenium Course Demo</a>.</p>
</div>