Skip to content

robertcdawson/getUniqueDomElements

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 

Repository files navigation

getUniqueDomElements - Improved Implementation

This JavaScript utility extracts all unique DOM element types that appear within the <body> element of a webpage. The original implementation has been completely rewritten to fix fundamental logic flaws and adopt modern JavaScript practices.

What's New

Fixed Core Logic: Now actually checks DOM hierarchy instead of relying on element order
Modern JavaScript: Uses ES6+ features, Set for O(1) uniqueness, arrow functions
Multiple Options: Three different implementations for various use cases
Error Handling: Proper null safety and error validation
Enhanced Features: Metadata support, configurable options, DOM analysis

Quick Start

Option 1: Simple Usage

// Load the script and run in console
getUniqueDomElements();
// Returns: ["DIV", "P", "SPAN", "IMG", ...] - only elements actually in body

Option 2: With Configuration Options

// More control over the output
getUniqueDomElementsRobust({
  toLowerCase: true,        // Get lowercase tag names
  includeContainer: true,   // Include the body tag itself
  sortResults: false       // Don't sort alphabetically
});

Option 3: With Rich Metadata

// Get detailed information about each element type
getUniqueDomElementsWithMetadata(true);
// Returns detailed objects with counts, first instances, attributes, etc.

Installation & Usage

Browser Console

  1. Open your browser's developer console
  2. Paste the contents of js/scripts.js
  3. Run any of the functions:
    getUniqueDomElements()
    runExamples()  // See all features demonstrated

In Your Web Page

<script src="js/scripts.js"></script>
<script>
  // Use immediately - functions are available globally
  console.log(getUniqueDomElements());
</script>

Test Page

Open test.html in your browser to see a comprehensive demonstration with:

  • Live examples of all function variants
  • Interactive testing with testInteractively()
  • Visual output and console logging
  • Various HTML elements for testing

API Reference

getUniqueDomElements()

Returns a sorted array of unique tag names found within the body element.

Returns: string[] - Array of uppercase tag names

getUniqueDomElementsRobust(options)

Advanced version with configuration options.

Parameters:

  • options.container (Element): Container to search within (default: document.body)
  • options.includeContainer (boolean): Include container tag (default: false)
  • options.toLowerCase (boolean): Return lowercase tags (default: false)
  • options.sortResults (boolean): Sort results alphabetically (default: true)

Returns: string[] - Array of tag names

getUniqueDomElementsWithMetadata(includeMetadata)

Enhanced version that can return detailed metadata about each element type.

Parameters:

  • includeMetadata (boolean): Whether to include metadata objects

Returns: string[] | Object[] - Tag names or metadata objects

analyzeDomStructure()

Utility function that provides comprehensive DOM analysis.

Returns: Object with DOM statistics including total elements, nesting depth, most/least common elements

testInteractively()

Interactive testing function that demonstrates functionality with different container elements.

Usage: Available in test.html - call from console to test with specific containers

getUniqueDomElementsLegacy()

Legacy compatibility wrapper that maintains backward compatibility while using the fixed implementation.

Note: Deprecated - use getUniqueDomElements() instead

Examples

// Basic usage - just unique tag names
getUniqueDomElements();
// → ["ARTICLE", "DIV", "H1", "P", "SPAN"]

// Lowercase tags, include body element
getUniqueDomElementsRobust({ 
  toLowerCase: true, 
  includeContainer: true 
});
// → ["article", "body", "div", "h1", "p", "span"]

// Rich metadata about each element type
getUniqueDomElementsWithMetadata(true);
// → [
//     {
//       tagName: "DIV",
//       count: 15,
//       firstInstance: <div class="container">,
//       firstInstanceAttributes: { class: "container", id: "main" },
//       firstInstanceClasses: ["container"]
//     },
//     ...
//   ]

// DOM structure analysis
analyzeDomStructure();
// → {
//     totalElements: 47,
//     uniqueElements: 8,
//     mostCommon: ["DIV", 15],
//     deepestNesting: 6,
//     elementFrequency: { "DIV": 15, "SPAN": 8, "P": 5, ... }
//   }

Key Improvements Over Original

Issue Original Improved
DOM Hierarchy ❌ Checked element order, not actual parent-child ✅ Uses querySelectorAll('*') for real descendants
Performance ❌ O(n²) indexOf() for uniqueness ✅ O(1) Set operations
Browser Support ❌ Unnecessary polyfills ✅ Modern ES6+ features
Error Handling ❌ No validation ✅ Null safety and error checking
Configurability ❌ Fixed behavior ✅ Multiple options and variants
Code Quality ❌ Verbose ES5 patterns ✅ Clean, modern JavaScript

Browser Compatibility

  • Modern Browsers: All features supported (Chrome 51+, Firefox 54+, Safari 10+)
  • Older Browsers: Core functionality works with minimal polyfills for Set if needed

Project Files

  • js/scripts.js - Main implementation with all functions and utilities
  • test.html - Comprehensive test page with live demonstrations
  • README.md - This documentation file
  • code_analysis.md - Detailed technical analysis of improvements

Development

The code includes comprehensive JSDoc comments and follows modern JavaScript best practices. Each function is thoroughly documented with parameter types and return values.

All functions are exposed globally on the window object for easy console access:

window.getUniqueDomElements
window.getUniqueDomElementsRobust  
window.getUniqueDomElementsWithMetadata
window.analyzeDomStructure
window.runExamples

To see all features in action, run:

runExamples();

This will demonstrate all three implementations with various options and show the DOM analysis features.

About

This function expression returns all unique DOM elements (within BODY) on a given web page.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors