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 unrelatedtype="search"inputs from other parts of the page.- Null check: The
if (targetInput)guard ensures we don't try to callfocus()on a non-existent element, which would throw an error. - Optional
break: If you know there's only one container with this search input, addingbreakstops 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
相关产品推荐
相关产品推荐

