为什么$(' .classname')& document.getElementsByClassName(' classname')返回不同的东西?

时间:2015-12-17 10:09:44

标签: javascript jquery html

为什么$(' .classname')只返回一个元素,当它的javascript等效document.getElementsByClassname(' classname')返回一个元素数组?如果它不是彼此的等价物,那么它是什么?如何使用jQuery获取具有相同类名的所有元素?除了$(' .classname')之外还有其他方法吗? 例如,

<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>

如果我使用document.getElementsByClassName(&#39; currentMonth&#39;),那么我将获得上面提到的所有元素的数组。

[ <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> ]

但是$('.currentMonth'),我只能看到一个元素。

如何使用$获取所有元素?

3 个答案:

答案 0 :(得分:5)

$('.currentMonth')返回所有匹配元素的jQuery对象。它以jQuery方式包装,但它也返回所有元素。您可以使用以下方法获取元素:

$('.currentMonth').each(function () {
  this; // Here this refers to each of the matched element.
});

document.getElementsByClassname('currentMonth')返回DOM对象列表。

例如,如果我正在执行这样的脚本:

$('.currentMonth').html("Hello!");

所有<td>都将被更改。

答案 1 :(得分:2)

$('.classname')是一个jQuery对象,而 document.getElementsByClassname('classname')是DOM对象的列表

$('.classname')将选择与类claaname匹配的所有元素,并将生成一个jQuery对象。

$('.classname').html("Whatever")将删除所有.classname元素。

答案 2 :(得分:0)

document.getElementsByClassname('classname') 

返回一个NodeList对象,表示具有指定类名的元素集合,使用浏览器内置方法,而$(".className")返回jQuery对象,你可以使用jQuery方法来操作它

Explore More

相关问题