You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让搜索过滤器对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 innerHTML with createElement to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:44:43