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

如何在不使用jQuery、querySelector系列方法的情况下用JavaScript获取id为slides的元素数组

How to Get All Elements with ID "slides" (No jQuery/Query Methods)

Since we can’t rely on querySelectorAll(), querySelector(), or jQuery, we can traverse every element in the DOM and collect those that match the id "slides". Here’s how to do it:

Method 1: Manual Loop (Great for Older Browser Compatibility)

This approach uses getElementsByTagName('*') to grab all elements, then loops through them to filter by id:

function getAllSlidesElements() {
  // Get every element in the document
  const allElements = document.getElementsByTagName('*');
  const slidesElements = [];
  
  // Loop through each element and check the id
  for (let i = 0; i < allElements.length; i++) {
    const currentElement = allElements[i];
    if (currentElement.id === 'slides') {
      slidesElements.push(currentElement);
    }
  }
  
  return slidesElements;
}

// Usage:
const slidesArray = getAllSlidesElements();
console.log(slidesArray); // Will contain all h1 elements with id="slides"

Method 2: Concise Modern Approach

If you’re targeting modern browsers, you can use Array.from() (or the spread operator) to convert the HTMLCollection to an array, then filter it directly:

// Using Array.from()
const slidesArray = Array.from(document.getElementsByTagName('*')).filter(element => {
  return element.id === 'slides';
});

// Using spread operator (even shorter)
const slidesArray = [...document.getElementsByTagName('*')].filter(el => el.id === 'slides');

A quick note: Having multiple elements with the same id is technically invalid HTML (ids should be unique per page). But this solution works perfectly for your given scenario where that’s the case.

内容的提问来源于stack exchange,提问作者Mamedul Islam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:43:04