Javascript 使用jQuery将类添加到第一个div

Javascript 使用jQuery将类添加到第一个div,javascript,jquery,html,css,Javascript,Jquery,Html,Css,如何使用jQuery将类添加到第一个div 我尝试了以下代码,但对我无效。 也许我错过了什么 <html> <head> <script src="http://code.jquery.com/jquery-1.8.2.js" type="text/javascript"></script> <script> $('.item') .eq(0).addClass('first').end() .eq(-1).addCla

如何使用jQuery将类添加到第一个div

我尝试了以下代码,但对我无效。 也许我错过了什么

<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.2.js" type="text/javascript"></script>
<script>
$('.item')
    .eq(0).addClass('first').end()
    .eq(-1).addClass('last').end();
</script>
<style type="text/css">
.first, .last{
background-color:#0099FF;
}
</style>
</head>
<body>
<div class="item">aaa</div>
<div class="item">bbb</div>
<div class="item">ccc</div>
<div class="item">ddd</div>
<div class="item">eee</div>
</body>
</html>

$(“.item”)
.eq(0).addClass('first').end()
.eq(-1).addClass('last').end();
.第一,最后{
背景色:#0099FF;
}
aaa
bbb
ccc
ddd
eee
编辑:谢谢大家,还有没有其他的div可以添加一个类呢?

试试看

$(document).ready(function() {
  $('.item:first-child').addClass('first');
});

您的代码是正确的,但它是在DOM准备就绪之前执行的,请将
移到
之前的最后一行

要将类添加到其余元素中,您可以这样做(从VisioN的)


您正在标记准备就绪之前执行代码。把代码包起来

// document ready short-style
$(function() {

});
参见jsfiddle


您的代码应该在DOM完全加载时执行。因此,请使用$(document.ready()

DOM层次结构完成后,即可运行脚本 构建。传递给.ready()的处理程序保证 在DOM准备好后执行,因此这通常是执行的最佳位置 附加所有其他事件处理程序并运行其他jQuery代码

大约$(document).ready()

检查下面的代码。它将帮助你完成你想做的事情

   $(document).ready(function() {
          $('.item').first().addClass('first');
        });
否则,即使在加载DOM之前也会运行js

$(“.item:first”).addClass('first')也可以正常工作

希望这能帮到你。如果你有任何问题,请不要犹豫。谢谢你试试这个

JS代码


您需要使用
$(function(){…})
来包装整个jQuery代码。

您可以始终使用直接的CSS,尽管它是CSS3。例如,您可以将当前CSS替换为:

.item:nth-of-type(1), .item:nth-of-type(3)
{
   background-color:#0099FF;
}
如果您只是想要jQuery,那么可以尝试:

$('.item:first').addClass('first');
$('.item:last').addClass('last');
你使用这个代码吗

$(function(){
   $(".item:first-child").addClass("anyclass");
})

or
  $("div:first-child").addClass("anyclass");

这是jQuery代码

<script>
$(document).ready(function(){
$('body .item:first').addClass('YOUR CLASS VALUE');
});
<script>

$(文档).ready(函数(){
$('body.item:first').addClass(“您的类值”);
});
问候,,

缺少DOM就绪:
$(function(){…})。编辑答案:
$(“.item:not(:first,:last)”).addClass(“newClass”)。每当有人发布jQuery问题时,这应该作为一个提醒。+1非常感谢,它现在可以工作了。如何将类添加到div的其余部分?正如其他人所提到的,jQuery需要在ready()函数中,否则它将在呈现页面之前运行。正确的选择器不应包含空格:
$(“.item:first”)
。更正。在演示中,它确实与一个空格一起工作。无论如何,谢谢你指出:-)
.item:nth-of-type(1), .item:nth-of-type(3)
{
   background-color:#0099FF;
}
$('.item:first').addClass('first');
$('.item:last').addClass('last');
$(function(){
   $(".item:first-child").addClass("anyclass");
})

or
  $("div:first-child").addClass("anyclass");
<script>
$(document).ready(function(){
$('body .item:first').addClass('YOUR CLASS VALUE');
});
<script>