goldies
    Preparing search index...

    Function domify

    • Convert an HTML string to a DOM element.

      Parses an HTML string using DOMParser and returns the first child element from the body of the resulting document. This is useful for creating DOM elements from HTML strings in a safe and efficient way.

      Parameters

      • html: string

        A valid HTML string to be converted to a DOM element

      Returns Element

      The first child element from the parsed HTML, or undefined if no elements exist

      When html parameter is not a string

      When the HTML string is invalid or results in no elements

      // Create a simple paragraph element
      const paragraph = domify('<p>Hello, World!</p>');
      console.log(paragraph?.tagName); // 'P'
      console.log(paragraph?.textContent); // 'Hello, World!'

      // Create a more complex element with attributes
      const link = domify('<a href="https://example.com" class="btn">Click me</a>');
      console.log(link?.getAttribute('href')); // 'https://example.com'
      console.log(link?.className); // 'btn'

      // Handle multiple elements (only first is returned)
      const firstDiv = domify('<div>First</div><div>Second</div>');
      console.log(firstDiv?.textContent); // 'First'
      // Type checking example
      const element = domify('<button type="submit">Submit</button>');
      if (element instanceof HTMLButtonElement) {
      console.log(element.type); // 'submit'
      }