简体   繁体   English

jQuery –仅选择第一个元素

[英]jQuery – select the first element only

How does one select an element ONLY if it's the first element within another element? 仅当元素是另一个元素中的第一个元素时,才如何选择它? In the examples below, I want to select and apply a margin-top of 0 if the h3 is ONLY the first element. 在下面的示例中,如果h3仅是第一个元素,我想选择并应用0的margin-top。

I thought this would work: 我认为这可以工作:

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

But this selects the first h3 in the div. 但这种选择在div第一H3。 So then I tried: 所以我尝试了:

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

But this doesn't seem to select anything. 但这似乎没有选择任何东西。

Any ideas? 有任何想法吗?

You can use the first-child 您可以使用第一个孩子

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

This will select a descendant h3 of .flexible-content-container .each-flexible-section .text-container which is the first child element of a parent 这将选择.flexible-content-container .each-flexible-section .text-container的后代h3,这是父级的第一个子元素

尝试这个:

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

There is multiple solutions , but i will correct yours : 有多种解决方案,但我会纠正您的问题:

$('.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');
    }
});

Other solutions: 其他解决方案:

  1. :first Selector :第一选择器

  2. :nth-child Selector :nth-​​child选择器

Use : first selector 用途:第一个选择器

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

or .first() .first()

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

Demo Fiddle 演示小提琴


If you have multiple .text-container classes, 如果您有多个.text-container类,

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

Try this: 尝试这个:

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

or: 要么:

$('.flexible-content-container .each-flexible-section .text-container').each(function(i) {

       $('h3:first', this).css('margin-top','0');

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM