如何让搜索过滤器对innerHTML创建的新元素生效?
Fixing Contact Search for Dynamically Added Items
Let's break down why your search isn't picking up new contacts and fix it right away:
The Core Issue
Your createContact function is appending new list items directly to the #demo div, but your search function (filter) is only looking for items inside the #names unordered list. That's why manually added contacts worked, but dynamic ones were invisible to the search—they were in the wrong container!
Updated JavaScript Code
Here's the fixed version with key improvements:
// CREATE NEW CONTACT document.getElementById('myForm').addEventListener('submit', createContact); function createContact(e) { e.preventDefault(); var newName = document.getElementById('create').value.trim(); // Don't add empty contacts if (!newName) return; // Target the actual contacts list instead of the demo div var namesList = document.getElementById('names'); // Create elements safely (avoids XSS risks vs innerHTML) var li = document.createElement('li'); li.className = 'menuItem'; var a = document.createElement('a'); a.href = '#'; a.textContent = newName; li.appendChild(a); namesList.appendChild(li); // Clear input after submission for better UX document.getElementById('create').value = ''; } // Search Filter var searchBox = document.getElementById('search'); searchBox.addEventListener('keyup', filter); function filter() { var ul = document.getElementById('names'); var liItems = ul.querySelectorAll('li.menuItem'); var searchValue = searchBox.value.toUpperCase(); for (var i = 0; i < liItems.length; i++) { var contactText = liItems[i].querySelector('a').textContent.toUpperCase(); // Toggle visibility based on search match liItems[i].style.display = contactText.includes(searchValue) ? '' : 'none'; } }
Key Fixes & Improvements
- Correct container for new contacts: Now we add new
<li>elements directly to#names—the same list your search function scans. - Safer element creation: Replaced
innerHTMLwithcreateElementto avoid potential security risks from untrusted user input, and ensures proper DOM integration. - Input validation: Blocks empty contact entries to keep your list clean.
- Cleaner search logic: Removed redundant variables and used
includes()for more readable match checking. - Better user experience: Clears the input field after submitting a new contact.
Give this a test—your search should now work for every contact, whether they're static in the HTML or dynamically added!
内容的提问来源于stack exchange,提问作者user9245313
相关产品推荐
相关产品推荐

