JavaScript:获取所有id类似于log_XXXX的对象

14

我需要获取所有id与特定模式匹配的对象。我该怎么做呢?谢谢!

3个回答

20

当前浏览器:

// DOM collection as proper array
const matches = Array.from(document.querySelectorAll('[id^=log_]'));

旧版浏览器:(IE9+)

// Use Array.prototype.slice to turn the DOM collection into a proper array
var matches = [].slice.call(document.querySelectorAll('[id^=log_]'));
jQuery:
$('[id^=log_]')

非常老的浏览器,没有使用jQuery:

var matches = [];
var elems = document.getElementsByTagName("*");
for (var i=0; i<elems.length; i++) {
  if (elems[i].id.indexOf("log_") == 0)
    matches.push(elems[i]);
}
//matches now is an array of all matching elements.

2
如果你不使用jQuery呢? :P - Dan Lew
2
你的jQuery选择器可以改进。 "星号选择器"是隐式的,你应该使用“以...开头”的选择器代替“包含”,并且下划线不需要转义:$("[id^=log_]") - Ben Blank
@openwonk 当我注意到我的回答被点赞或评论并且它们已经过时时,我会尽力整理它们... :-) 期待Array.from更普遍地可用。 - Tracker1
这让我离我所寻找的东西太近了。当我在控制台中记录此对象时,我观察到它打印整个对象而不是ID(当我展开对象时可用)。有什么想法可以只获取ID吗? - Yash Saraiya
1
@YashSaraiya 很晚才回复,但 matches.map(m => m.id) 将给你 ID 列表。 - Tracker1
这里有一个完整的答案:https://dev59.com/Emoy5IYBdhLWcg3wMLOj - eric_the_animal

3

好的,这里是一个直接的JavaScript答案:

// a handy function to aid in filtering:
// takes an array and a function, returns another array containing
// only those elements for which f() returns true
function filter(a, f) 
{ 
  var ret = []; 
  for (var i=0; i<a.length; ++i) 
  {
    if ( f(a[i]) ) 
      ret.push(a[i]); 
  }
  return ret;
}

// this collects all elements in the current document
var elements = document.getElementsByTagName("*");

// and this filters out all but those that match our pattern
var logElements = filter(elements, function(el) 
  { return /log_/.test(el.id) } ); // simple expression

-1
最好使用JS框架来实现这个,因为它们有先进的DOM选择器功能,可以让您想要做的事情变得非常容易。有很多可供选择,但更流行的是jQueryPrototypeMooToolsDojo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接