querySelectorAll和getElementsBy *方法返回什么? [英] What do querySelectorAll and getElementsBy* methods return?

查看:144
本文介绍了querySelectorAll和getElementsBy *方法返回什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行 getElementsByClassName (以及类似的函数,例如 getElementsByTagName querySelectorAll )与 getElementById 一样工作,还是返回一个元素数组?

Do getElementsByClassName (and similar functions like getElementsByTagName and querySelectorAll) work the same as getElementById or do they return an array of elements?

我问的原因是因为我试图使用 getElementsByClassName 更改所有元素的样式。见下文。

The reason I ask is because I am trying to change the style of all elements using getElementsByClassName. See below.

//doesn't work
document.getElementsByClassName('myElement').style.size = '100px';

//works
document.getElementById('myIdElement').style.size = '100px';


推荐答案

您的 getElementById()代码有效,因为ID必须是唯一的,因此函数总是只返回一个元素(或 null ,如果没有找到)。

Your getElementById() code works since IDs have to be unique and thus the function always returns exactly one element (or null if none was found).

但是, getElementsByClassName () querySelectorAll() ,以及其他 getElementsBy * 方法返回一个类似数组的元素集合。像对待真实数组一样迭代它:

However, getElementsByClassName(), querySelectorAll(), and other getElementsBy* methods return an array-like collection of elements. Iterate over it like you would with a real array:

var elems = document.getElementsByClassName('myElement');
for(var i = 0; i < elems.length; i++) {
    elems[i].style.size = '100px';
}

如果你喜欢更短的东西,可以考虑使用 jQuery

If you prefer something shorter, consider using jQuery:

$('.myElement').css('size', '100px');

这篇关于querySelectorAll和getElementsBy *方法返回什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆