본문 바로가기

제이쿼리

[제이쿼리] 전체 형(이전) / 동생(다음) 요소 선택자

전체 형 요소 선택자는 선택한 요소를 기준으로 이전에 오는 전체 형제 요소를 선택한다. 그리고 전체 동생 요소 선택자는 선택한 요소를 기준으로 다음에 오는 전체 형제 요소를 선택한다.

 

기본형 : $("요소 선택").prevAll(), $("요소 선택").nextAll()

 

예제. class 값이 txt인 요소를 기준으로 이전에 오는 형제 요소와 다음에 오는 형제 요소를 확인하자

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

<script>

$(function() {
    var style_1 = {
        "background-color" : "#0ff",
        "border" : "2px solid #f00"
    }
    var style_2 = {
        "background-color" : "#ff0",
        "border" : "2px dashed #f00"
    }

    $(".txt").prevAll().css(style_1);
    $(".txt").nextAll().css(style_2);
});

</script>

<p>wrap밖</p>

<div id="wrap">
    <h1>인접 관계 선택자</h1>
    <p>내용1</p>
    <p class="txt">내용2</p>
    <p>내용3</p>
    <p>내용4</p>
</div>

    
</body>
</html>

결과