Skip to main content
Glama

get-element-html

Retrieve HTML content of web elements using CSS selectors with configurable depth control for inspecting DOM structure during development.

Instructions

Retrieves the HTML content of a specific element and its children with optional depth control

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
selectorYesCSS selector of the element to inspect
includeOuterNoIf true, includes the selected element's outer HTML; otherwise returns only inner HTML (default: false)
depthNoControl HTML depth limit: -1 = unlimited (default), 0 = text only, 1+ = limited depth with deeper elements shown as <!-- omitted -->

Implementation Reference

  • The handler function that executes the tool logic: waits for the element, evaluates JavaScript to extract HTML (inner/outer) with optional depth limiting using DOM cloning and trimming, constructs response with metadata and HTML content.
    async ({ selector, includeOuter = false, depth = -1 }) => {
      try {
        // Check browser status
        const browserStatus = getContextForOperation();
        if (!browserStatus.isStarted) {
          return browserStatus.error;
        }
    
        // Check if element exists
        await browserStatus.page.waitForSelector(selector, { state: 'visible', timeout: 5000 });
    
        // Get element's HTML content with depth control
        const htmlContent = await browserStatus.page.evaluate(({ selector, includeOuter, depth }: { selector: string; includeOuter: boolean; depth: number }) => {
          const element = document.querySelector(selector);
          if (!element) return null;
          
          // Handle unlimited depth (backward compatibility)
          if (depth === -1) {
            return includeOuter ? element.outerHTML : element.innerHTML;
          }
          
          // Handle text-only mode
          if (depth === 0) {
            return element.textContent || '';
          }
          
          // Handle depth-limited mode with DOM cloning
          const cloned = element.cloneNode(true) as Element;
          
          function trimDepth(node: Element, currentDepth: number) {
            if (currentDepth >= depth) {
              // Replace content with omitted marker
              node.innerHTML = '<!-- omitted -->';
              return;
            }
            
            // Process child elements
            Array.from(node.children).forEach(child => {
              trimDepth(child, currentDepth + 1);
            });
          }
          
          // Start depth counting from appropriate level
          trimDepth(cloned, includeOuter ? 0 : 1);
          
          return includeOuter ? cloned.outerHTML : cloned.innerHTML;
        }, { selector, includeOuter, depth });
    
        if (htmlContent === null) {
          return {
            content: [
              {
                type: 'text',
                text: `Element with selector "${selector}" not found`
              }
            ],
            isError: true
          };
        }
    
        // Result message construction
        const resultMessage = {
          selector,
          htmlType: depth === 0 ? 'textContent' : (includeOuter ? 'outerHTML' : 'innerHTML'),
          depth,
          depthLimited: depth !== -1,
          length: htmlContent.length,
          checkpointId: await getCurrentCheckpointId(browserStatus.page)
        };
    
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(resultMessage, null, 2)
            },
            {
              type: 'text',
              text: htmlContent
            }
          ]
        };
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        Logger.error(`Failed to get element HTML: ${errorMessage}`);
        return {
          content: [
            {
              type: 'text',
              text: `Failed to get element HTML: ${errorMessage}`
            }
          ],
          isError: true
        };
      }
    }
  • Zod input schema defining parameters for the get-element-html tool: selector (required), includeOuter (optional boolean), depth (optional integer >= -1).
      selector: z.string().describe('CSS selector of the element to inspect'),
      includeOuter: z.boolean().optional().describe("If true, includes the selected element's outer HTML; otherwise returns only inner HTML (default: false)"),
      depth: z.number().int().min(-1).optional().describe('Control HTML depth limit: -1 = unlimited (default), 0 = text only, 1+ = limited depth with deeper elements shown as <!-- omitted -->')
    },
  • Direct registration of the 'get-element-html' tool using server.tool(), including description, input schema, and handler function.
    server.tool(
      'get-element-html',
      'Retrieves the HTML content of a specific element and its children with optional depth control',
      {
        selector: z.string().describe('CSS selector of the element to inspect'),
        includeOuter: z.boolean().optional().describe("If true, includes the selected element's outer HTML; otherwise returns only inner HTML (default: false)"),
        depth: z.number().int().min(-1).optional().describe('Control HTML depth limit: -1 = unlimited (default), 0 = text only, 1+ = limited depth with deeper elements shown as <!-- omitted -->')
      },
      async ({ selector, includeOuter = false, depth = -1 }) => {
        try {
          // Check browser status
          const browserStatus = getContextForOperation();
          if (!browserStatus.isStarted) {
            return browserStatus.error;
          }
    
          // Check if element exists
          await browserStatus.page.waitForSelector(selector, { state: 'visible', timeout: 5000 });
    
          // Get element's HTML content with depth control
          const htmlContent = await browserStatus.page.evaluate(({ selector, includeOuter, depth }: { selector: string; includeOuter: boolean; depth: number }) => {
            const element = document.querySelector(selector);
            if (!element) return null;
            
            // Handle unlimited depth (backward compatibility)
            if (depth === -1) {
              return includeOuter ? element.outerHTML : element.innerHTML;
            }
            
            // Handle text-only mode
            if (depth === 0) {
              return element.textContent || '';
            }
            
            // Handle depth-limited mode with DOM cloning
            const cloned = element.cloneNode(true) as Element;
            
            function trimDepth(node: Element, currentDepth: number) {
              if (currentDepth >= depth) {
                // Replace content with omitted marker
                node.innerHTML = '<!-- omitted -->';
                return;
              }
              
              // Process child elements
              Array.from(node.children).forEach(child => {
                trimDepth(child, currentDepth + 1);
              });
            }
            
            // Start depth counting from appropriate level
            trimDepth(cloned, includeOuter ? 0 : 1);
            
            return includeOuter ? cloned.outerHTML : cloned.innerHTML;
          }, { selector, includeOuter, depth });
    
          if (htmlContent === null) {
            return {
              content: [
                {
                  type: 'text',
                  text: `Element with selector "${selector}" not found`
                }
              ],
              isError: true
            };
          }
    
          // Result message construction
          const resultMessage = {
            selector,
            htmlType: depth === 0 ? 'textContent' : (includeOuter ? 'outerHTML' : 'innerHTML'),
            depth,
            depthLimited: depth !== -1,
            length: htmlContent.length,
            checkpointId: await getCurrentCheckpointId(browserStatus.page)
          };
    
          return {
            content: [
              {
                type: 'text',
                text: JSON.stringify(resultMessage, null, 2)
              },
              {
                type: 'text',
                text: htmlContent
              }
            ]
          };
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : String(error);
          Logger.error(`Failed to get element HTML: ${errorMessage}`);
          return {
            content: [
              {
                type: 'text',
                text: `Failed to get element HTML: ${errorMessage}`
              }
            ],
            isError: true
          };
        }
      }
    );
  • src/index.ts:87-92 (registration)
    Top-level call to registerBrowserTools which includes the registration of get-element-html among other browser tools.
    registerBrowserTools(
      server,
      contextManager,
      lastHMREvents,
      screenshotHelpers
    );
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions retrieving HTML with depth control but doesn't cover critical aspects like whether this requires an active browser session, potential performance impacts, error handling, or what happens if the selector doesn't match. For a tool with no annotation coverage, this leaves significant gaps in understanding its behavior.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, well-structured sentence that efficiently conveys the core functionality without unnecessary words. It's front-loaded with the main purpose and includes key optional features, making it easy to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of interacting with browser elements and the lack of annotations and output schema, the description is incomplete. It doesn't explain what the return value looks like (e.g., HTML string format), error conditions, or dependencies on other tools like 'start-browser'. For a tool with no structured safety or output information, more context is needed.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all three parameters thoroughly. The description adds minimal value beyond the schema by mentioning 'optional depth control' in general terms, but doesn't provide additional syntax, examples, or context that isn't already covered in the parameter descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with specific verbs ('retrieves') and resources ('HTML content of a specific element and its children'), making it easy to understand what the tool does. However, it doesn't explicitly differentiate from sibling tools like 'get-element-properties' or 'get-element-styles', which might retrieve different aspects of elements.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage through the mention of 'optional depth control' and the context of retrieving HTML, suggesting it's for inspecting web elements. However, it lacks explicit guidance on when to use this tool versus alternatives like 'get-console-logs' or 'capture-screenshot', and doesn't specify prerequisites or exclusions.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/ESnark/blowback'

If you have feedback or need assistance with the MCP directory API, please join our Discord server