[英]why does $('.classname') & document.getElementsByClassName('classname') return different things?
Why does $('.classname') return just one element when it's javascript equivalent document.getElementsByClassname('classname') returns an array of elements? 为什么$('。classname')与javascript等价的文档只返回一个元素。getElementsByClassname('classname')返回一个元素数组? If it's not each other's equivalent, what is then?
如果不是彼此相等,那又是什么? How to get all the element which have the same class name using jQuery?
如何使用jQuery获取具有相同类名的所有元素? Is there any other way other than $('.classname') ?
除了$('。classname')以外,还有其他方法吗? For example,
例如,
<tr>
<td class="currentMonth">1</td>
<td class="currentMonth">2</td>
<td class="currentMonth">3</td>
<td class="currentMonth">4</td>
<td class="currentMonth">5</td>
If i use document.getElementsByClassName('currentMonth'), then I will get an array of all the elements mentioned above. 如果我使用document.getElementsByClassName('currentMonth'),那么我将获得上述所有元素的数组。
[ <td class="currentMonth">1</td>, <td class="currentMonth">2</td>, <td class="currentMonth">3</td>, <td class="currentMonth">4</td>, <td class="currentMonth">5</td> ]
But with $('.currentMonth')
, I can see only one element. 但是使用
$('.currentMonth')
,我只能看到一个元素。
How can I get all the elements using $
? 如何使用
$
获得所有元素?
The $('.currentMonth')
returns a jQuery object of all the matching elements. $('.currentMonth')
返回所有匹配元素的jQuery对象。 It is wrapped in the jQuery way, but it also returns all the elements. 它以jQuery方式包装,但它也返回所有元素。 You can get the elements by using:
您可以使用以下方法获取元素:
$('.currentMonth').each(function () {
this; // Here this refers to each of the matched element.
});
Whereas document.getElementsByClassname('currentMonth')
returns a list of DOM Objects. 而
document.getElementsByClassname('currentMonth')
返回DOM对象的列表。
So for example, if I am executing a script like this: 因此,例如,如果我正在执行这样的脚本:
$('.currentMonth').html("Hello!");
All the <td>
s will be changed. 所有
<td>
都将被更改。
$('.classname')
is a jQuery Object, whereas document.getElementsByClassname('classname')
is a list of DOM Object $('.classname')
是一个jQuery对象,而document.getElementsByClassname('classname')
是一个DOM对象列表
$('.classname')
will select all the elements which matches with the class claaname
and will make a jQuery Object of it. $('.classname')
将选择与类claaname
匹配的所有元素,并将其制成jQuery Object。
$('.classname').html("Whatever")
will remove all the .classname
elements. $('.classname').html("Whatever")
将删除所有.classname
元素。
document.getElementsByClassname('classname')
return a NodeList
object , representing collection of elements with specified class name,using browsers built-in methods while $(".className")
return jQuery object and you can use jQuery methods to manipulate it 使用浏览器的内置方法返回
NodeList
对象,该对象表示具有指定类名称的元素的集合,而$(".className")
返回jQuery对象,您可以使用jQuery方法进行操作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.