카테고리 없음

jQuery 조회범위 제한

푸곰주 2023. 5. 13. 09:45

이전에  Element 객체에서 getElementsBy* 메소드를 실행하면 조회의 범위가 그 객체의 하위 엘리먼트로 제한된다는 것을 알아봤다. jQuery에서는 어떻게 이러한 작업을 할 수 있을까?

selector context

가장 간편한 방법은 조회할 때 조회 범위를 제한하는 것이다. 그 제한된 범위를 jQuery에서는 selector context라고 한다.

<ul>
    <li class="marked">html</li>
    <li>css</li>
    <li id="active">JavaScript
        <ul>
            <li>JavaScript Core</li>
            <li class="marked">DOM</li>
            <li class="marked">BOM</li>
        </ul>
    </li>
</ul>
<script src="https://code.jquery.com/jquery-3.7.0.js" integrity="sha256-JlqSTELeR4TLqP0OG9dxM7yDPqX1ox/HfgiSLBj8+kM=" crossorigin="anonymous"></script>
<script>
    // $( ".marked", "#active").css( "background-color", "red" ); 밑에와 동일한 결과
    $("#active .marked").css("background-color", "red");
</script>

 

$("#active.marked").css("background-color", "red");      (X)

$("#active .marked").css("background-color", "red");      (O)

 

active(id) .marked(clss) 사이에 띄어쓰기 써주기

 

 

.find()

find는 jQuery 객체 내에서 엘리먼트를 조회하는 기능을 제공한다. 아래의 코드는 위의 예제와 효과가 같다.


    $('#active').find('.marked').css("background-color", "red");

 

 

find를 쓰는 이유는 체인을 끊지 않고 작업의 대상을 변경하고 싶을 때 사용한다

 

id값 active --> blue 폰트를 사용하고

marked classname에대해서만 background-color -->red 배경색을 준 코드


    $('#active').css('color', 'blue').find('.marked').css('background-color', 'red');

 

 

더 많은 예제는 jQuery의 메뉴얼을 참고하자. .find()