jQuery 공작소 : :first-of-type

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

:first-of-type 셀렉터는 지정한 요소중 첫번째 것을 찾습니다.

예제 1
기본 예제
보기
버튼을 눌러보세용

span span
span span
span span
소스
<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;
    }
    .css_test img {
        border : 5px solid silver;
        vertical-align : middle; /* span을 세로 중앙으로 정렬시키기 위함 */
    }
    .css_test span {
        border : 5px solid silver;
        padding : 5px;
    }
</style>

버튼을 눌러보세용<br><br>
<button type="button" onclick="j_test('span')">first-of-type 의 span</button>
<button type="button" onclick="j_test('img')">first-of-type 의 img</button>

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

<script type="text/javascript">
    function j_test(v){
        $('.css_test div ' + v + ':first-of-type').css('border-color', 'blue');

        // 0.5초후 원복
        setTimeout(function(){
            $('.css_test div ' + v + ':first-of-type').css('border-color', '');
        }, 500);
    }
</script>
관련 CSS
jQuery

$( '.css_test  div  span:first-of-type' )  -  클래스명이 css_test 요소의 div첫번째 span 들을 찾습니다.

- :first-child 셀렉터와 유사하지만 찾는 대상을 특정할 수 있습니다.
- :first 와는 다릅니다. :first 는오직 처음것 한개만 찾습니다.

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