【问题标题】:jQuery – select the first element onlyjQuery – 只选择第一个元素
【发布时间】:2026-02-21 20:45:02
【问题描述】:

只有当它是另一个元素中的第一个元素时,如何选择一个元素?在下面的示例中,如果 h3 只是第一个元素,我想选择并应用 0 的 margin-top。

我认为这会起作用:

$('.flexible-content-container .each-flexible-section .text-container h3').each(function() {
    if ( $(this).is(':first-of-type') ) {
        $(this).css('margin-top','0');
    }
});

但这会选择 div 中的第一个 h3。于是我尝试了:

$('.flexible-content-container .each-flexible-section .text-container h3').each(function() {
    if ( $(this).is(':first') ) {
        $(this).css('margin-top','0');
    }
});

但这似乎没有选择任何东西。

有什么想法吗?

【问题讨论】:

  • $('.flexible-content-container .each-flexible-section .text-container h3:first').css('margin-top','0'); - 使用这个
  • @rdck 这取决于你的 html 标记,你介意也发布一下吗。

标签: jquery html jquery-selectors


【解决方案1】:

您可以使用first-child

$('.flexible-content-container .each-flexible-section .text-container h3:first-child').css('margin-top','0');

这将选择 .flexible-content-container .each-flexible-section .text-container 的后代 h3,它是父元素的第一个子元素

【讨论】:

  • 您的意思是用:first-child 代替:first-of-type 吗?在孩子之后检查类型似乎是多余的。
  • @BoltClock 忘记检查每个循环中发生了什么,......这本身不是必需的
【解决方案2】:

试试这个:

$('.flexible-content-container .each-flexible-section .text-container h3:first-child').css('margin-top','0');

【讨论】:

    【解决方案3】:

    有多种解决方案,但我会纠正你的:

    $('.flexible-content-container .each-flexible-section .text-container h3').each(
     function(index , value) {
        if ( index == 0 ) {//if it's the first element
            $(this).css('margin-top','0');
        }
    });
    

    其他解决方案:

    1. :first Selector

    2. :nth-child Selector

    【讨论】:

      【解决方案4】:

      使用: first选择器

      $('.flexible-content-container .each-flexible-section .text-container h3:first').css('margin-top','0');
      

      .first()

      $('.flexible-content-container .each-flexible-section .text-container h3').first().css('margin-top','0');
      

      Demo Fiddle


      如果您有多个 .text-container 类,

      $('.flexible-content-container .each-flexible-section .text-container').each(function(){
          $(this).find('h3:first').css('margin-top','0').css('color','red');
      });
      

      【讨论】:

      • 我发布的内容,你看到了吗?在您的评论行中。
      • 对,如果是层级 +1。
      • 我的意思是如果有多个.text-containers??
      【解决方案5】:

      试试这个:

      $('.flexible-content-container .each-flexible-section .text-container').each(function(i) {
          if (i === 0) {
             $('h3', this).css('margin-top','0');
          }
      });
      

      或:

      $('.flexible-content-container .each-flexible-section .text-container').each(function(i) {
      
             $('h3:first', this).css('margin-top','0');
      
      });
      

      【讨论】: