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

HTML元素子元素遍历及指定类容器内目标search输入框聚焦实现

Solution to Focus the Search Input in the Specific Container

Got it, let's work through this problem step by step. You already have a solid start with code that grabs all md-select-menu-container elements—now we just need to narrow down to the right one and target its search input.

Here's how to adjust your code to set focus on the correct input:

// Convert the HTMLCollection of containers into an array
const containers = Array.from(document.getElementsByClassName('md-select-menu-container'));

// Loop through each container to find the one with the search input
for (const container of containers) {
  // Search ONLY within the current container for the search input
  const targetInput = container.querySelector('input[type="search"]');
  
  // If we found the input, set focus and exit the loop (optional if you only need the first match)
  if (targetInput) {
    targetInput.focus();
    break; // Remove this line if you need to focus all matching inputs across containers
  }
}

Quick breakdown of what's happening:

  • container.querySelector(...): This is the key change—instead of searching the entire DOM, we're limiting the search to the current container element. That way we won't pick up unrelated type="search" inputs from other parts of the page.
  • Null check: The if (targetInput) guard ensures we don't try to call focus() on a non-existent element, which would throw an error.
  • Optional break: If you know there's only one container with this search input, adding break stops the loop as soon as we find it—saves a bit of unnecessary processing.

If you need to target a container with extra conditions (like one that's visible or active), you can add a check, for example:

if (targetInput && container.classList.contains('is-active')) {
  targetInput.focus();
  break;
}

内容的提问来源于stack exchange,提问作者Peter Boomsma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:48:43