CSS vs DOM Manipulation for Hiding Elements: Detailed Analysis #

Overview #

There are three primary approaches to hiding elements in browser scripts:

  1. CSS-based hiding (ATProtoTweaks.js): display: none !important in a <style> tag
  2. JavaScript hide (bsky-cleaner.js hide mode): element.style.setProperty('display', 'none', 'important')
  3. JavaScript remove (bsky-cleaner.js remove mode): element.remove()

Each has distinct benefits and trade-offs.


1. CSS-Based Hiding (display: none !important in <style> tag) #

Implementation (ATProtoTweaks.js): #

button[data-testid="postBookmarkBtn"] {
    display: none !important;
}

Benefits ✅ #

1. Performance #

  • Browser-native CSS processing: The browser's CSS engine handles hiding directly in the rendering pipeline
  • No JavaScript execution overhead: CSS rules are applied during style recalculation, which is highly optimized
  • Batch processing: All matching elements are hidden simultaneously without iterating in JavaScript
  • GPU-accelerated: Modern browsers optimize CSS display changes at the rendering engine level

2. Application Timing #

  • Applies before JavaScript execution: CSS is processed early in the page load cycle
  • Prevents flash of unwanted content (FOUC): Elements are hidden before they're visible
  • Lower CPU usage: No JavaScript event loop involvement

3. Simplicity #

  • Declarative: One rule handles all matching elements
  • No iteration needed: Browser handles matching automatically
  • Less code: Minimal implementation required
  • Easier to understand: CSS is self-documenting

4. Persistence #

  • Consistent across DOM changes: CSS rules persist even if elements are re-added to DOM
  • No tracking needed: No need to track which elements have been processed
  • Works with dynamically added content: New elements matching the selector are automatically hidden

5. Memory Efficiency #

  • No JavaScript object references: Doesn't store element references in memory
  • Browser-native storage: CSS rules are stored efficiently in the browser's stylesheet system
  • No WeakSet/Set overhead: Doesn't require tracking data structures

Detriments ❌ #

1. Flexibility #

  • No conditional logic: Can't hide elements based on runtime conditions (e.g., user preferences, element content)
  • No dynamic behavior: Can't change hiding behavior based on state or context
  • Limited selectors: CSS selectors have limitations (can't easily inspect text content, parent conditions, etc.)

2. Inspection & Debugging #

  • Harder to debug: CSS rules are less visible in DevTools console
  • No runtime feedback: Can't log which elements were hidden
  • Difficult to verify: Need to inspect Computed Styles to see why element is hidden

3. Reversibility #

  • Difficult to toggle: Must remove/modify the entire <style> tag to show elements again
  • No programmatic control: Can't easily enable/disable at runtime
  • Override complexity: Need to add more specific CSS to override

4. Specificity Issues #

  • Selector specificity: Might not work if more specific styles override it
  • Must use !important: Can cause issues with existing CSS if not careful
  • Cascade conflicts: May conflict with other CSS rules

5. No Additional Actions #

  • Can't perform side effects: Can't log, track, or perform other operations when hiding
  • No data collection: Can't count hidden elements or gather statistics

2. JavaScript Hide (element.style.setProperty('display', 'none', 'important')) #

Implementation (bsky-cleaner.js): #

element.style.setProperty('display', 'none', 'important');

Benefits ✅ #

1. Flexibility & Control #

  • Conditional logic: Can hide elements based on runtime conditions
  • Dynamic behavior: Can inspect element properties, content, or context before hiding
  • Programmatic control: Easy to enable/disable hiding at runtime
  • Custom logic: Can implement complex rules (e.g., "hide if text contains X")

2. Inspection & Debugging #

  • Console logging: Can log which elements were hidden and why
  • Debug mode: Easy to add debug output for troubleshooting
  • DevTools visibility: Inline styles are clearly visible in Elements panel
  • Runtime inspection: Can query and verify hidden elements in console

3. Reversibility #

  • Easy to toggle: Can set display to original value or '' to restore
  • Programmatic control: Can implement show/hide toggles
  • State management: Can track original display values for restoration

4. Tracking & Statistics #

  • Count elements: Can track how many elements were hidden
  • Data collection: Can gather statistics or analytics
  • Audit trail: Can log actions for debugging or reporting

5. Integration with JavaScript #

  • Event handling: Can trigger events before/after hiding
  • Side effects: Can perform additional operations (analytics, cleanup, etc.)
  • Conditional hiding: Can check element state, parent context, etc.

Detriments ❌ #

1. Performance #

  • JavaScript execution overhead: Requires JS to run and iterate through elements
  • DOM queries: Must call querySelectorAll() which traverses the DOM tree
  • Style recalculation: Each style.setProperty() triggers style recalculation
  • Event loop blocking: Synchronous operations block the main thread

2. Timing Issues #

  • May see flash of content: Elements may be visible briefly before script runs
  • Execution timing: Must wait for DOM to be ready
  • Race conditions: May hide elements after they've already rendered
  • SPA navigation: Need MutationObserver to catch dynamically added elements

3. Complexity #

  • More code: Requires iteration, error handling, tracking
  • State management: Need to track processed elements (WeakSet) to avoid duplicates
  • Error handling: Must handle selector failures, missing elements, etc.
  • More moving parts: MutationObserver, debouncing, initialization logic

4. Memory Usage #

  • Element references: WeakSet stores references to processed elements
  • Closures: Functions may hold references to elements
  • Observer overhead: MutationObserver keeps references to watched nodes

5. Duplicate Processing #

  • Need tracking: Must use WeakSet or similar to avoid processing same element twice
  • Re-applying rules: On SPA navigation, must detect and skip already-hidden elements
  • Edge cases: Must handle elements that are removed and re-added

3. JavaScript Remove (element.remove()) #

Implementation (bsky-cleaner.js): #

element.remove();

Benefits ✅ #

1. Complete Removal #

  • Truly gone: Element is removed from DOM, not just hidden
  • No layout impact: Removed elements don't affect layout calculations
  • Memory cleanup: Browser can garbage collect removed elements (eventually)
  • No style recalculation: Removed elements don't participate in rendering at all

2. Simpler Mental Model #

  • No display property manipulation: Element simply doesn't exist
  • Can't be accidentally shown: No risk of CSS or JavaScript showing it again
  • Clean DOM: DOM tree doesn't contain unwanted elements

3. No Inheritance Issues #

  • No child element visibility: Children are removed too (no need to worry about nested elements)
  • No CSS inheritance: Removed elements don't participate in CSS cascade

4. Performance (Partial) #

  • No rendering: Removed elements don't consume rendering resources
  • Smaller DOM tree: Smaller DOM = faster queries and operations
  • No style calculations: No styles need to be computed for removed elements

Detriments ❌ #

1. Irreversibility #

  • Can't restore: Once removed, element is gone (unless you store references)
  • No undo: Hard to restore if user wants to show element again
  • State loss: Element's original state (styles, event listeners) is lost

2. Re-adding Elements #

  • SPA challenges: If SPA re-adds elements, they'll appear again (need MutationObserver)
  • Dynamic content: Must constantly watch for and remove re-added elements
  • More processing: Must re-process on every DOM change

3. Event Listener Cleanup #

  • Potential memory leaks: If elements had event listeners, they may not be cleaned up properly
  • Reference issues: Other code may hold references to removed elements

4. Layout Reflow #

  • Immediate reflow: Removing elements triggers immediate layout recalculation
  • Performance cost: Layout reflow can be expensive, especially with many removals
  • Visual jank: User may see layout shifts

5. Compatibility Issues #

  • JavaScript required: Won't work if JS is disabled (rare but possible)
  • Timing sensitive: Must run after elements exist in DOM
  • Selector failures: If selector doesn't match, nothing happens silently

Performance Comparison #

CSS Approach (ATProtoTweaks) #

Initial Load:
├─ CSS parsing: ~0.1ms
├─ Selector matching: ~0.5ms (browser-optimized)
└─ Style application: ~0.1ms
Total: ~0.7ms for all matching elements

On DOM Changes:
├─ Browser automatically re-applies CSS
└─ No JavaScript execution needed

JavaScript Hide #

Initial Load:
├─ DOM ready wait: ~50-200ms (varies)
├─ querySelectorAll: ~1-5ms (depends on DOM size)
├─ Iteration + style.setProperty: ~2-10ms per element
├─ Style recalculation: ~1-3ms per element
└─ WeakSet operations: ~0.1ms per element
Total: ~4-18ms per element + initialization overhead

On DOM Changes (MutationObserver):
├─ Observer fires: ~1ms
├─ Debounce delay: 300ms (configurable)
├─ Re-query + process: ~4-18ms per new element
└─ Skip already-processed: ~0.1ms per check

JavaScript Remove #

Initial Load:
├─ Same as JavaScript Hide
└─ Additional: Layout reflow: ~5-20ms (depends on layout complexity)

On DOM Changes:
├─ Same as JavaScript Hide
└─ Additional: Reflow on each removal: ~5-20ms

Winner for Performance: CSS approach (fastest, especially with many elements)


Real-World Scenarios #

Scenario 1: Static Page with Known Selectors #

Best Choice: CSS

  • Elements are present on initial load
  • Selectors are stable
  • No need for conditional logic
  • ATProtoTweaks approach is optimal

Scenario 2: Dynamic SPA with User Preferences #

Best Choice: JavaScript Hide

  • Need to handle dynamically added content
  • User may want to toggle visibility
  • Need debug logging
  • bsky-cleaner hide mode is optimal

Scenario 3: Permanent Removal, No Restoration Needed #

Best Choice: JavaScript Remove

  • Elements should never appear
  • Clean DOM is important
  • Performance on initial load matters less than ongoing rendering
  • bsky-cleaner remove mode is optimal

Scenario 4: Conditional Hiding Based on Content #

Best Choice: JavaScript Hide/Remove

  • Need to inspect element text/content
  • Need complex logic (e.g., "hide if contains 'spam'")
  • CSS selectors can't do content inspection
  • Must use JavaScript approach

Hybrid Approach (Best of Both Worlds) #

You could combine both approaches:

// Use CSS for initial, always-on hiding (fast)
const style = document.createElement('style');
style.textContent = `
    button[data-testid="postBookmarkBtn"] {
        display: none !important;
    }
`;
document.head.appendChild(style);

// Use JavaScript for conditional/dynamic hiding (flexible)
function hideConditionalElements() {
    document.querySelectorAll('.some-element').forEach(el => {
        if (shouldHide(el)) { // Custom logic
            el.style.setProperty('display', 'none', 'important');
        }
    });
}

Benefits:

  • Fast initial hiding (CSS)
  • Flexible conditional hiding (JavaScript)
  • Best of both worlds

Recommendations by Use Case #

Use CSS (display: none !important) When: #

✅ You want maximum performance
✅ Selectors are simple and stable
✅ Hiding should be permanent and always-on
✅ No conditional logic needed
✅ You want to prevent FOUC (flash of unwanted content)
✅ Elements are present on initial page load

Use JavaScript Hide (style.setProperty) When: #

✅ You need conditional/dynamic hiding
✅ You want to toggle visibility at runtime
✅ You need debug logging or tracking
✅ You need to inspect element content/properties
✅ You want user-configurable behavior
✅ Elements are added dynamically (SPAs)

Use JavaScript Remove (element.remove()) When: #

✅ You want elements completely gone from DOM
✅ You never need to restore elements
✅ Layout efficiency is critical
✅ You want cleaner DOM structure
✅ Memory cleanup is important


Specific Comparison: Bookmark Hiding #

ATProtoTweaks Approach (CSS): #

button[data-testid="postBookmarkBtn"] {
    display: none !important;
}

Pros:

  • ✅ Fastest (browser-native CSS)
  • ✅ No JavaScript execution
  • ✅ Works immediately on page load
  • ✅ Handles all matching elements automatically
  • ✅ Persistent across SPA navigation (if style tag persists)

Cons:

  • ❌ Can't log which elements were hidden
  • ❌ Can't count hidden elements
  • ❌ Harder to debug
  • ❌ Can't conditionally hide (e.g., "hide only on profile pages")
  • ❌ Must modify CSS to enable/disable

bsky-cleaner Approach (JavaScript): #

// Hide mode
element.style.setProperty('display', 'none', 'important');

// Remove mode
element.remove();

Pros:

  • ✅ Can log actions (debug mode)
  • ✅ Can count processed elements
  • ✅ Easy to enable/disable via settings
  • ✅ Can add conditional logic
  • ✅ Better for user configuration

Cons:

  • ❌ Slower (JavaScript execution + DOM queries)
  • ❌ May see brief flash of content
  • ❌ Needs MutationObserver for SPA
  • ❌ More complex code
  • ❌ Requires tracking to avoid duplicates

Conclusion #

For bookmark hiding specifically:

  1. If you want maximum performance and simplicity: Use CSS (ATProtoTweaks approach)
  2. If you want flexibility and debugging: Use JavaScript hide (bsky-cleaner hide mode)
  3. If you want permanent removal: Use JavaScript remove (bsky-cleaner remove mode)

For most users: CSS approach is sufficient unless you need:

  • Runtime configuration
  • Debug logging
  • Conditional hiding
  • User preferences

The performance difference is usually negligible for small numbers of elements, but CSS scales better with many elements.