본문 바로가기
JQuery

230217 JQuery 노드제어

제이쿼리 이웃,형제 노드조작

$("선택자").노드조작()

  • .closest() : 근접 단일부모요소 탐색. 몇단구조든간에 최근접부모를 한번에 찾음. 여러번 올라갈 필요가 없다. 선택자를 넣으면 원하는 최근접태그로 한번에 갈 수가 있다. 선택자로는 태그명을 넣어도 되고, 아이디나 클래스를 넣어도 됨.
  • .find("선택자") : 특정 자식요소 탐색.
  • .children() : 자식요소 탐색
  • .first() : 자식요소중 첫번째. firstElementChild
  • .last() : 자식요소중 마지막
  • .next() : 다음형제노드 nextElementChild
  • .prev() : 이전형제노드
  • .siblings() : 모든 형제노드


※fn.init =>계속해서 jquery 적용가능
first(), find()와 last()는 children()이 적용된 후에 사용.

이외에도 여러 태그들이 있다. 구글링

 

 

 

jquery06.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- jquery -->
    <script src="js/jquery-3.6.3.min.js"></script>
</head>
<body>
    
    <table class="xxx">
        <tr>
            <th>번호</th>
            <th>이름</th>
            <th>버튼</th>
            <th>테스트</th>
        </tr>
        <tr>
            <td>1</td>
            <td>홍길동</td>
            <td>
                <button type="button" class="btn">버튼</button>
            </td>
            <td>
                <span><i class="test">테스트1</i></span>
                <span >테스트2</span>
            </td>
        </tr>
        <tr>
            <td>2</td>
            <td>이순신</td>
            <td>
                <button type="button" class="btn">버튼</button>
            </td>
            <td>
                <span><i class="test">테스트1</i></span>
                <span >테스트2</span>
            </td>
        </tr>
    </table>

    <script>
        /*
         1.closest("선택자") - 최근접 단일 부모 선택
         2.prev() -이전형제
         3.next() -다음형제
         4.siblings() -모든형제
         5.first() -첫번째 자식
         6.last() -마지막 자식
         7.children() -모든자식
         8.find("선택자") -특정 자식
        */
        $(".btn").click(function(e){
            //this or e.target
            //console.log(this);
            //console.log(e.target);
            // console.log($(this).closest("td"));
            // console.log($(this).closest("tr")); //최근접 tr태그
            // console.log($(this).closest(".xxx")); //최근접 xxx클래스

            // console.log( $(this).closest("td").prev()); //이전형제
            // console.log( $(this).closest("td").next()); //다음형제
           //console.log( $(this).closest("td").siblings()); //모든형제

           //console.log($(this).closest("tr").children()); //모든자식들
           //console.log($(this).closest("tr").children().first()); //첫째
           //console.log($(this).closest("tr").children().last()); //막내

           //console.log($(this).closest("tr").find(".test")); //.test 자식
           console.log($(this).closest("tr").find("span")); //모든 span태그 자식
           

        })


    </script>
</body>
</html>