How to hide span element if anchor href attribute is empty using JavaScript?

In web development, it's common to hide elements based on certain conditions. One specific requirement is hiding a <span> element when its associated <a> element has an empty href attribute. This is useful for navigation menus or dynamically generated links.

This article explores multiple JavaScript approaches to achieve this functionality, giving you the flexibility to choose the method that best fits your needs.

Understanding the Problem

We want to hide a <span> element if its associated <a> element has an empty href attribute. To accomplish this, we need to:

  • Select the <a> elements that need checking

  • Check if the href attribute is empty

  • Hide or show the corresponding <span> element accordingly

Method 1: On Page Load Check

The most straightforward approach checks all links when the page loads and hides spans for empty hrefs:

<!DOCTYPE html>
<html>
<head>
    <title>Hide Span on Empty Href</title>
</head>
<body>
    <a href="https://example.com">Valid Link</a>
    <span>Span 1 - Should be visible</span>
    <br><br>
    
    <a href="">Empty Href Link</a>
    <span>Span 2 - Should be hidden</span>
    <br><br>
    
    <a href="#section">Hash Link</a>
    <span>Span 3 - Should be visible</span>

    <script>
        // Check all links on page load
        document.addEventListener('DOMContentLoaded', function() {
            const links = document.querySelectorAll('a');
            
            links.forEach(function(link) {
                // Check if href is empty string
                if (link.getAttribute('href') === '') {
                    // Hide the next sibling span
                    const nextSpan = link.nextElementSibling;
                    if (nextSpan && nextSpan.tagName === 'SPAN') {
                        nextSpan.style.display = 'none';
                    }
                }
            });
        });
    </script>
</body>
</html>

In this example, the span following the link with empty href will be hidden automatically when the page loads.

Method 2: Using CSS with JavaScript Detection

This approach combines CSS and JavaScript for better performance:

<!DOCTYPE html>
<html>
<head>
    <title>Hide Span with CSS + JS</title>
    <style>
        .hide-span {
            display: none;
        }
    </style>
</head>
<body>
    <a href="https://tutorialspoint.com">TutorialsPoint</a>
    <span>Visible span</span>
    <br><br>
    
    <a href="">No destination</a>
    <span>This span will be hidden</span>
    <br><br>
    
    <a href="javascript:void(0)">JavaScript void</a>
    <span>This span stays visible</span>

    <script>
        function hideSpansForEmptyLinks() {
            const links = document.querySelectorAll('a');
            
            links.forEach(function(link) {
                const href = link.getAttribute('href');
                const nextSpan = link.nextElementSibling;
                
                if (nextSpan && nextSpan.tagName === 'SPAN') {
                    if (href === '' || href === null) {
                        nextSpan.classList.add('hide-span');
                    } else {
                        nextSpan.classList.remove('hide-span');
                    }
                }
            });
        }
        
        // Run on page load
        document.addEventListener('DOMContentLoaded', hideSpansForEmptyLinks);
    </script>
</body>
</html>

Method 3: Dynamic Monitoring with MutationObserver

For dynamic content, use MutationObserver to watch for changes:

function createDynamicHiding() {
    function checkAndHideSpans() {
        const links = document.querySelectorAll('a');
        
        links.forEach(function(link) {
            const nextSpan = link.nextElementSibling;
            if (nextSpan && nextSpan.tagName === 'SPAN') {
                const href = link.getAttribute('href');
                nextSpan.style.display = (href === '' || href === null) ? 'none' : '';
            }
        });
    }
    
    // Initial check
    checkAndHideSpans();
    
    // Watch for changes
    const observer = new MutationObserver(checkAndHideSpans);
    observer.observe(document.body, {
        childList: true,
        subtree: true,
        attributes: true,
        attributeFilter: ['href']
    });
    
    return observer;
}

// Usage: createDynamicHiding();

Comparison of Methods

Method Performance Dynamic Content Complexity
Page Load Check Fast No Simple
CSS + JavaScript Fast Manual trigger needed Simple
MutationObserver Good Yes Complex

Key Considerations

  • getAttribute() vs href property: Use getAttribute('href') to get the exact attribute value

  • Element relationship: Examples assume span immediately follows the anchor tag

  • Performance: For static content, use Method 1. For dynamic content, use Method 3

  • CSS classes vs inline styles: CSS classes are generally preferred for maintainability

Conclusion

Choose the page load check method for static content, CSS+JavaScript for better styling control, or MutationObserver for dynamic content. The getAttribute() method ensures accurate empty href detection.

Updated on: 2026-03-15T23:19:01+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements