elements / add remove
Advanced element
Add / Remove Elements
Practicing dynamic DOM mutation, element collections, index asserting, and handling StaleElementReferenceException in automation test suites.
Dynamic Element Generator
0 items- add button
- #btn-add-element
- container
- #elements-container
- items
- .added-manually
- expected
- Clicking 'Add Element' appends a red 'Delete' button; clicking a delete button removes that specific element.
Code snippets
Python (Selenium)
# Click Add 3 times
for _ in range(3):
driver.find_element(By.ID, "btn-add-element").click()
buttons = driver.find_elements(By.CSS_SELECTOR, ".added-manually")
assert len(buttons) == 3
# Delete the second button
buttons[1].click()
# Re-query elements to avoid stale element reference
remaining = driver.find_elements(By.CSS_SELECTOR, ".added-manually")
assert len(remaining) == 2TypeScript (Playwright)
// Click Add 3 times
for (let i = 0; i < 3; i++) {
await page.click('#btn-add-element');
}
const items = page.locator('.added-manually');
await expect(items).toHaveCount(3);
// Delete first item
await items.first().click();
await expect(items).toHaveCount(2);