element_exists
Check if a page element exists using CSS, text, or testid selectors. Returns a simple exists or not found status to confirm presence before interaction.
Instructions
Quick check if an element exists on the page. Ultra-lightweight alternative to query_selector_all when you only need existence confirmation. Returns simple exists/not found status. Most common check before attempting interaction. Supports testid shortcuts.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| selector | Yes | CSS selector, text selector, or testid shorthand (e.g., 'testid:submit-button', '#main') |
Implementation Reference
- The execute() method of ElementExistsTool class - the core logic. Uses createScopedLocator to find elements, counts matches, and returns formatted existence status (✓ exists or ✗ not found). For found elements, it extracts tag/id/class info for a concise summary.
async execute(args: ElementExistsArgs, context: ToolContext): Promise<ToolResponse> { return this.safeExecute(context, async (page) => { const locator = await this.createScopedLocator(page, args.selector); const count = await locator.count(); if (count === 0) { return { content: [ { type: 'text', text: `✗ not found: ${args.selector}` } ], isError: false }; } // Get element info for better output const element = locator.first(); const elementInfo = await element.evaluate((el) => { const tag = el.tagName.toLowerCase(); const parts: string[] = [tag]; if (el.id) parts.push(`#${el.id}`); if (el.className && typeof el.className === 'string') { const classes = el.className.split(' ').filter(c => c).slice(0, 2); if (classes.length) { classes.forEach(c => parts.push(`.${c}`)); } } return parts.join(''); }).catch(() => args.selector); if (count === 1) { return { content: [ { type: 'text', text: `✓ exists: <${elementInfo}>` } ], isError: false }; } // Multiple matches return { content: [ { type: 'text', text: `✓ exists: <${elementInfo}> (${count} matches)` } ], isError: false }; }); } - Input schema for element_exists tool: requires a 'selector' string (CSS selector, text selector, or testid shorthand).
inputSchema: { type: "object", properties: { selector: { type: "string", description: "CSS selector, text selector, or testid shorthand (e.g., 'testid:submit-button', '#main')" } }, required: ["selector"], }, }; - src/tools/browser/register.ts:86-86 (registration)Registration of ElementExistsTool in the browser tools registry (line 86), alongside other inspection tools.
ElementExistsTool, - TypeScript interface ElementExistsArgs defining the 'selector' string argument.
export interface ElementExistsArgs { selector: string; } - Evaluation helper that suggests using element_exists when the user writes querySelector !== null checks.
if (scriptLower.match(/\!=\s*null|\!==\s*null/) && scriptLower.match(/queryselector/)) { suggestions.push({ key: 'exists', line: '✓ element_exists — boolean + summary (vs querySelector !== null)' }); }