如何筛选pre标签内的文本行?适配多容器场景需求
Alright, let's figure out how to filter lines inside <pre> tags to only show matches for your search term—while keeping the container visible even when there's no match, and handling multiple identical divs. Here's a practical approach:
Step 1: Set up your HTML structure
First, let's define the containers and search input. I'll use a shared class for all code containers so we can target them easily:
<!-- Multiple identical code containers --> <div class="code-container"> <pre> Line 1: apple Line 2: banana Line 3: zebra Line 4: cherry </pre> </div> <div class="code-container"> <pre> Line A: cat Line B: dog Line C: fox Line D: zebu </pre> </div> <!-- Search input --> <input type="text" id="searchInput" placeholder="Search for a term...">
Step 2: JavaScript logic to filter lines
The core idea is to preserve the original text of each <pre> so we don't lose data on repeated searches, filter lines based on the input, and handle empty matches gracefully:
const searchInput = document.getElementById('searchInput'); const codeContainers = document.querySelectorAll('.code-container'); // Save original text for each pre when the page loads codeContainers.forEach(container => { const pre = container.querySelector('pre'); pre.dataset.originalText = pre.textContent.trim(); }); // Handle search input changes searchInput.addEventListener('input', function() { const searchTerm = this.value.trim().toLowerCase(); codeContainers.forEach(container => { const pre = container.querySelector('pre'); const originalLines = pre.dataset.originalText.split('\n'); // Filter lines that include the search term (case-insensitive) let filteredLines = originalLines.filter(line => line.toLowerCase().includes(searchTerm) ); // If no matches, show a placeholder instead of hiding the block if (filteredLines.length === 0) { filteredLines = ['⚠️ No matching lines found']; } // Update the pre content with filtered lines (keeps line breaks intact) pre.textContent = filteredLines.join('\n'); }); });
Key details to note:
- Preserving original content: We store the full unmodified text in a
data-*attribute (data-originalText) so every search uses the complete original content—no accidental data loss from repeated filtering. - Handling multiple containers: Using
querySelectorAll('.code-container')lets us loop through every matching div, so this works seamlessly no matter how many containers you have. - Empty match fallback: Instead of clearing the
<pre>entirely, we show a friendly message to ensure the container stays visible. - Case insensitivity: Converting both the search term and lines to lowercase ensures matches work regardless of capitalization (you can remove this if you want case-sensitive searches).
Optional enhancements:
- Debounce the search: If you have a lot of code blocks, add a debounce function to delay the filter until the user stops typing (reduces unnecessary re-renders).
- Exact matches: Replace
includes()with a regex for precise matching, e.g.,line.match(new RegExp(\b${searchTerm}\b, 'i'))for whole-word matches. - Code highlighting support: If you're using a library like Prism.js for syntax highlighting, re-trigger highlighting after updating the
<pre>content:// After updating pre.textContent Prism.highlightElement(pre);
内容的提问来源于stack exchange,提问作者securisec
相关产品推荐
相关产品推荐

