How do I display only the visible text with jQuery?

To display only the visible text in jQuery, use the :visible selector. This selector targets elements that are currently visible on the page (not hidden with display:none, visibility:hidden, or other hiding methods).

Syntax

$(selector).filter(':visible')
$(selector + ':visible')
$(':visible')

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Visible Text with jQuery</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div id="myDiv">
        <span class="test" style="display:none"><b>Hidden Text</b></span>
        <span class="demo"><b>Visible Text</b></span>
        <p style="visibility:hidden">Another Hidden Element</p>
        <p>Another Visible Element</p>
    </div>
    
    <div id="output"></div>
    
    <script>
        // Get only visible text from children
        var visibleText = $('#myDiv').children(':visible').text();
        $('#output').html('<strong>Visible text: </strong>' + visibleText);
        
        // Alternative: Get all visible elements
        console.log('All visible elements:', $('#myDiv :visible').length);
    </script>
</body>
</html>

Output

Visible text: Visible TextAnother Visible Element

Different Methods

Method 1: Get Text from Visible Children

<div id="container">
    <p style="display:none">Hidden paragraph</p>
    <p>Visible paragraph 1</p>
    <p>Visible paragraph 2</p>
</div>

<script>
    var text = $('#container').children(':visible').text();
    console.log(text); // "Visible paragraph 1Visible paragraph 2"
</script>

Method 2: Get Each Visible Element Separately

<script>
    $('#container').children(':visible').each(function() {
        console.log($(this).text());
    });
    // Output:
    // "Visible paragraph 1"
    // "Visible paragraph 2"
</script>

Key Points

  • The :visible selector excludes elements with display:none, visibility:hidden, or zero dimensions
  • Use children(':visible') to target only direct visible children
  • Use find(':visible') or :visible to target all visible descendants
  • The text() method concatenates text from all selected elements

Comparison

Method Scope Use Case
children(':visible') Direct children only First-level visible elements
find(':visible') All descendants All nested visible elements
filter(':visible') Current selection Filter existing jQuery object

Conclusion

Use jQuery's :visible selector to target only visible elements and extract their text content. This is essential for dynamic interfaces where elements are shown/hidden based on user interaction.

Updated on: 2026-03-15T23:18:59+05:30

580 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements