jQuery 공작소 : :first-child

jQuery 공작소에 방문해 주셔서 감사드립니다. 쉬운 예제로 느껴보세요!!

:first-child 셀렉터는 첫번째 자식요소들을 찾습니다.

예제 1
지정한 대상의 첫번째 것을 찾는 예제
보기
소스
<style type="text/css">
    .css_test {
        border-radius : 5px;
        border : 5px solid gray;
        padding : 10px;
    }
</style>

<button type="button" onclick="$('.css_test img:first-child').animate({width:'+=10'})">첫번째 자식은 커집니다</button>

<div class="css_test">
    <img src="//superkts.com/img/css/huk.gif" />
    <img src="//superkts.com/img/css/huk.gif" />
    <img src="//superkts.com/img/css/huk.gif" />
</div>
관련 CSS
예제 2
:first 셀렉터와 :first-child 의 차이점 보기
보기
버튼을 눌러보세용

소스
<style type="text/css">
    .css_test {
        background : #efefef;
        border-radius : 5px;
        border : 5px solid gray;
    }
    .css_test div {
        background : #fff;
        border-radius : 5px;
        margin : 10px;
        padding : 10px;
    }
</style>

버튼을 눌러보세용<br><br>
<button type="button" onclick="j_test_fc()">first-child 는 봅니다</button>
<button type="button" onclick="j_test_f()">first 는 봅니다</button>

<div class="css_test">
    <div>
        <img src="//superkts.com/img/huk1.gif" />
        <img src="//superkts.com/img/huk1.gif" />
        <img src="//superkts.com/img/huk1.gif" />
        <img src="//superkts.com/img/huk1.gif" />
    </div>
    <div>
        <img src="//superkts.com/img/huk1.gif" />
        <img src="//superkts.com/img/huk1.gif" />
        <img src="//superkts.com/img/huk1.gif" />
        <img src="//superkts.com/img/huk1.gif" />
    </div>
    <div>
        <img src="//superkts.com/img/huk1.gif" />
        <img src="//superkts.com/img/huk1.gif" />
        <img src="//superkts.com/img/huk1.gif" />
        <img src="//superkts.com/img/huk1.gif" />
    </div>
</div>

<script type="text/javascript">
    function j_test_fc(){ // first-child
        $('.css_test div img:first-child').attr('src', '//superkts.com/img/huk2.gif');
        setTimeout(function(){
            // 0.5초후 원복
            $('.css_test img').attr('src', '//superkts.com/img/huk1.gif');
        }, 500);
    }

    function j_test_f(){ // first
        $('.css_test div img:first').attr('src', '//superkts.com/img/huk2.gif');
        setTimeout(function(){
            // 0.5초후 원복
            $('.css_test img').attr('src', '//superkts.com/img/huk1.gif');
        }, 500);
    }
</script>
관련 CSS
jQuery

$( '.css_test div img:first-child' )
- 클래스명이 css_test 인 요소의 div 안의 img첫번째 자식만 찾기
- 각 div 안에 있는 이미지중 첫번째 것들 즉 첫번째 자식만 찾습니다.
- 예제에서는 각 3개의 div 중 첫번째 이미지들이 대상입니다.
- 각 div 가 부모이고 그 안의 첫번째 것을 의미하죠.

$( '.css_test div img:first' )
- 클래스명이 css_test 인 요소의 div 안의 img첫번째 것만 찾기
- 찾아진 이미지를 전체로 놓고 판단하여 첫번째 것만 찾습니다.
- 무조건 첫번째 것만 찾는것이죠.

+ 관련 jQuery +
jQuery 홈페이지 :first-child API 문서 : http://api.jquery.com/first-child-selector/