2021.03.29 국비교육 56일차

[TOC]

traverse 필터 선택자

filter(fn)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    $(function(){
        //1차 필터링 후 2차 필터링 (일치하는 selector) 
        $("li").filter(function(idx, ele){ //인덱스, 요소를 받음
            console.log(idx, ele.innerText);
            return ele.innerText == "A4"; //ture인 경우 element return // A4출력
        })//filter fuction
        .css("color", "red")
        .end()
        .filter(function(idx, ele){
            return idx%3 ==0; //A1, A4, A7
        }).css("font-size", "40px").end();

    })//

</script>
</head>
<body>
<p>Hello</p>
<ul>
    <li>A1</li>
    <li>A2</li>
    <li class = "my">A3</li>
    <li>A4</li>
    <li>A5</li>
    <li id = "a">A6</li>
    <li>A7</li>
    <li>A8</li>
</ul>
</body>
</html>

not

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">


    $(function(){
        $("li").not(".my").css("color", "red") //A3 제외한 모두
        .end()
        .not(":even").css("font-size", "40px"); //A2, A4, A6, A8
    })

</script>
</head>
<body>
<p>Hello</p>
<ul>
    <li>A1</li>
    <li>A2</li>
    <li class = "my">A3</li>
    <li>A4</li>
    <li>A5</li>
    <li id = "a">A6</li>
    <li>A7</li>
    <li>A8</li>
</ul>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">


    $(function(){
        $("li").not(function(idx, ele){
            console.log(ele)
            return ele.innerText == "A4"; //A4제외한 모든 태그 
        }).css("color", "red")
        .end()
        .not(function(idx, ele){
            return idx % 3 ==0; 
        }).css("font-size", "40px") //A2, A3, A5,A6,A8 적용됨 
    });    
</script>
</head>
<body>
<p>Hello</p>
<ul>
    <li>A1</li>
    <li>A2</li>
    <li class = "my">A3</li>
    <li>A4</li>
    <li>A5</li>
    <li id = "a">A6</li>
    <li>A7</li>
    <li>A8</li>
</ul>
</body>
</html>

is

  • 요소가 있으면 true 없으면 false값 반환
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    $(function(){

        //1차 필터링 후 2차 선택자와 일치하는 요소 있으면 true 아니면 false
        var x = $("li").is(".my"); //if문 활용해서 태그 유무 확인
        console.log(x); //true
    })    

    $(function(){
        var y = $("li").is(function(idx, ele){
            console.log("ele: ", ele);
            console.log("this : ", this.innerText); //ele 출력한거랑 결과 같음
            return ele.innerText == "A8";
        });

        console.log(y); //true 출력

        var fnx = $("li").is(function(idx, ele){
            var fnele = $(ele); //javascript -> jQuery객체 전환
            console.log(fnele);
            //console.log(fnele.innerText); //undefined
            return fnele.text() == "A8";
        })

        console.log(fnx); //true
    })



</script>
</head>
<body>
<p>Hello</p>
<ul>
    <li>A1</li>
    <li>A2</li>
    <li class = "my">A3</li>
    <li>A4</li>
    <li>A5</li>
    <li id = "a">A6</li>
    <li>A7</li>
    <li>A8</li>
</ul>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    $(function() {
        $("li").click(kkk);
    })

    function kkk(event){ //함수선언
        //console.log(event.target); //javascript
        var target = $(event.target); //jQuery 객체로 이벤트 발생요소 저장 
        // 클릭된 li의 태그
        console.log(target);
        if(target.is("li")){
            console.log("==========");
            target.css("background-color", "green");

            var isStrong = target.is(function(){
                console.log("isString >>");
                console.log($("strong", this)); //event발생한 곳에서 strong만 선택
                //strong태그를 찾은뒤 li에 쌓인 것
                console.log($("strong", this).length); //strong 있으면 1
                return $("strong", this).length == 1;
            })

            if(isStrong){
                target.css("font-size", "30px");
            }
        }

    }
</script>
</head>
<body>
    <p>Hello</p>
    <p>Hello</p>
    <ul>
        <li>A1</li>
        <li>A2</li>
        <li>A3</li>
        <li>A<strong>4</strong></li>
        <li>A5</li>
    </ul>

</body>
</html>

has

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    $(function() {
        $("li").has("ul").css("background-color", "yellow"); //li태그중 ul태그를 갖고 있는 요소
    })
</script>
</head>
<body>

    <p>Hello</p>
    <ul>
        <li>A1</li>
        <li>A2</li>
        <li>A3
            <ul>
                <li>B1</li>
                <li>B2</li>
                <li>B3</li>
            </ul>
        </li>
        <li>A4</li>
    </ul>

</body>
</html>

map

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    $(function() {
        //1차 이후 가공해서 배열로 변환
        var arr =  $("li").map(function(idx, ele){ //배열로 변환 index, element
            console.log("this >>", this, "ele >> ", ele, "$(this).text() >>", $(this).text()); //fn함수 사용
            //return ele.innerText.toLowerCase()
            return $(this).text().toLowerCase(); // == ele.innerText, == $(ele).text() == this.innerText
            //element의 문자를 소문자로변경 리턴
        })


        console.log("arr >> ", arr)
    })

</script>
</head>
<body>

    <p>Hello</p>
    <ul>
        <li>A1</li>
        <li>A2</li>
        <li>A3
            <ul>
                <li>B1</li>
                <li>B2</li>
                <li>B3</li>
            </ul>
        </li>
        <li>A4</li>
    </ul>


</body>
</html>

slice

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    $(function() {
        //1차 이후 subset반환 idnex = 0부터
        $("li").slice(4).css("color", "red") //A5 A6 A7 적용, index = 4부터 적용
        .end()
        .slice(0,3).css("font-size", "40px"); // index 0 이상 3 미만까지 적용
    })

</script>
</head>
<body>
<p>Hello</p>
<ul>
 <li>A1</li>
 <li>A2</li>
 <li>A3</li>
 <li>A4</li>
 <li>A5</li>
 <li>A6</li>
 <li>A7</li>
</ul>
</body>
</html>

add

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function(){
        //li를 검색, 또한 p도 검색$("div", p")와 동일
        //본인 태그 뒤에 적용하는 css만 적용함
        $("li").css("border", "2px solid black").add("p").css("color", "blue");

    })

</script>
</head>
<body>
<p>Hello</p>
<ul>
 <li>A1</li>
 <li>A2</li>
 <li>A3</li>
 <li>A4</li>
 <li>A5</li>
 <li>A6</li>
 <li>A7</li>
 <li>A8</li>
</ul>

</body>
</html>

addBack

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function() { //div이후 p만 선택이 아닌 addback을 통해 #x와 p 자식이 포함됨

        $("#x").find("p").addBack().css("color", "red");
        //addBack 전 : B만 선택
        //addBack 후 : A, B 선택

    })
</script>
</head>
<body>
    <div id="x">
        A
        <p>B</p>
    </div>
    <div>
        C
        <p>B</p>
    </div>

</body>
</html>

contents

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function() { 

        console.log($("li").find("ul").contents());
        $("li").find("ul").contents().css("color", "red");

    })
</script>
</head>
<body>
    <ul>
        <li>A</li>
        <li>A2</li>
        <li>A3
            <ul>
                <li>B</li>
                <li>B2</li>
                <li>B3</li>
            </ul>
        </li>
        <li>A4</li>
    </ul>

</body>
</html>

traversing_tree

children, find

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function() {
        //children은 자식까지만
        $("div").children("span").css("color", "red"); //홍길동만

        //find는 자손까지
        $("div").find("span").css("font-size", "40px"); //홍길동, 강감찬
    })
</script>
</head>
<body>
    <div>
        <span>홍길동</span>
    </div>
    <div>
        유관순
        <p>
            <span>강감찬</span>
        </p>
    </div>

</body>
</html>

closest, parents

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function() {
        //현재 요소 시작하여 selector와 일치하는 요소를 찾을때까지 조상으로 이동

        //0개 또는 1개 요소 반환
        $("span").closest("div").css("color", "red"); //B, C만 적용

        //현재 요소의 부모요소에서 시작, 루트요소까지 상위의 요소를 모두 담음, 0개 이상의 요소
        $("span").parents("div").css("font-size", "30px"); //전부다 적용
    })
</script>
</head>
<body>
    <div>
        start
        <div>
            A
            <div>
                B
                <p>
                    <span>C</span>
                </p>
            </div>
        </div>
    </div>

</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function() {
        //현재 요소의 부모부터 시작, 루트까지 모두 추가
        $("p").parents().css("color","red"); //A, B, C, D 모두 적용
        $("p").parents("#my").css("font-size","40px"); //p태그의 부모중 id가 my인 것만

    })
</script>
</head>
<body>
    <div>
        A
        <div>
            B
            <p>C</p>
        </div>
    </div>
    <div id="my">
        <p>D</p>
    </div>

</body>
</html>

parent

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function() {
        //바로 위 부모 선택, 여러개 선택가능, 배열로 반환
        $("p").parent().css("color","red"); //B, C, D 적용
        $("p").parent("#my").css("font-size","40px"); //p태그의 부모중 id가 my인 것만

    })
</script>
</head>
<body>
    <div>
        A
        <div>
            B
            <p>C</p>
        </div>
    </div>
    <div id="my">
        <p>D</p>
    </div>

</body>
</html>

next

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function(){
        $("div").next().css("color", "red"); //div제외 div의 바로 뒤 형제 적용(1개) A2, B2, C2, C3
        $("div").next(".my").css("font-size", "40px"); //뒤에 있는 것중 my태그 인것 // B2, C2

    });

</script>
</head>
<body>
    <div>A</div>
    <p>A2</p>
    <div>B</div>
    <p class="my">B2</p>
    <div>C</div>
    <div class="my">C2</div>
    <p>C3</p>

</body>
</html>

nextAll

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function(){
        //선택 요소의 selector와 일치하는 모든 형제 요소(0개 이상)
        //selector가없는 경우 모든 형제 반환
        $("div:first").nextAll().css("color", "red"); // A2, B, B2, C, C2, C3
        $("div:first").nextAll(".my").css("font-size", "30px");  //B2, C2


    });

</script>
</head>
<body>
    <div>A</div>
    <p>A2</p>
    <div>B</div>
    <p class="my">B2</p>
    <div>C</div>
    <div class="my">C2</div>
    <p>C3</p>

</body>
</html>

prev

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function(){
        //select 바로 앞 형제요소
        $("div").prev().css("color", "red") //A2, B2, C
        $("div").prev(".my").css("font-size", "40px") //B2

    });

</script>
</head>
<body>
    <div>A</div>
    <p>A2</p>
    <div>B</div>
    <p class="my">B2</p>
    <div>C</div>
    <div class="my">C2</div>
    <p>C3</p>

</body>
</html>

prevAll

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function(){
        //select 바로 앞 형제요소
        $("div:last").prevAll().css("color", "red") //C, B2, B, A2, A
        $("p:last").prevAll(".my").css("font-size", "40px") //C2, B2

    });

</script>
</head>
<body>
    <div>A</div>
    <p>A2</p>
    <div>B</div>
    <p class="my">B2</p>
    <div>C</div>
    <div class="my">C2</div>
    <p>C3</p>

</body>
</html>

siblings

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function(){ //앞 뒤 모든 형제 요쇼

        $("p").siblings().css("color", "red"); //전부다
        $("p").siblings(".my").css("font-size", "40px"); //B2, C2
    });

</script>
</head>
<body>
    <div>A</div>
    <p>A2</p>
    <div>B</div>
    <p class="my">B2</p>
    <div>C</div>
    <div class="my">C2</div>
    <p>C3</p>

</body>
</html>

속성 이용하여 값 추출하기

val

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    $(function(){

        $("button").on("click", function(){
                    //.click(fn)도 가능
                var userid = $("#userid").val();
                var passwd = $("#passwd").val(); //getter
                console.log(userid, passwd); 

                $("#passwd2").val(passwd); //setter
                console.log($("#selTest").val()); //select val

        })

    })

</script>
</head>
<body>

    <select id="selTest">
        <option value="test">test</option>
    </select> 아이디:
    <input type="text" name="userid" id="userid" value="아이디입력">
    <!-- 
        js : document.getElementById("userid").getAttribute("value"), value 
        jQuery : $("#userid").val()    
    -->
    <br> 비번:
    <input type="text" name="passwd" id="passwd" value="비번입력">
    <input type="text" name="passwd" id="passwd2">
    <br>
    <button>OK</button>

</body>
</html>

text

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    $(function(){

        $("button").on("click", function(){
            console.log($("#x").text()); //getter
            var data = $("#x").text();
            $("#result").text(data); //setter

        })

    })

</script>
</head>
<body>

    <p id="x"><span>홍길동</span></p>
    <div id="result"></div>
    <button>OK</button>

</body>
</html>

html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    $(function(){

        $("button").on("click", function(){
            var data = $("#x").html(); //innerHTML
            console.log(data);
            $("#result").html("<h1>" + data + "</h1>"); //setter

        })

    })

</script>
</head>
<body>

    <p id="x"><span>홍길동</span></p>
    <div id="result"></div>
    <button>OK</button>

</body>
</html>

attr

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    $(function(){

        $("button").on("click", function(){
            var img = $("img"); 
            var data = $("img").attr("src"); // img.src , img.getAttribute("src")

            console.log(img);
            console.log(data);

            //img.attr("src", "b.jpg"); //set
            img.attr({"src" : "b.jpg", "width" : "300", "height" : "200"}); 
        })

    })

</script>
</head>
<body>

    <img src = "a.jpg" width = "100" height ="100">
    <button>ok</button>

</body>
</html>

removeAttr

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    $(function(){

        $("#xxx").on("click", function(){
            $("#my").removeAttr("checked"); //평가대비 코드
        })

        $("#yyy").on("click", function(){
            $("#my").attr("checked", "checked"); //평가대비 코드
        })

    })

</script>
</head>
<body>

    A<input id = "my" type = "checkbox" name = "my" checked = "checked"><br>

    <button id = "xxx">해제</button>
    <button id = "yyy">설정</button>

</body>
</html>

prop

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    $(function(){

        //prop 검증 true, false, 리턴
        $("button").on("click", function(){
            console.log($("#my").attr("checked")); //checked 출력
            console.log($("#my").prop("checked")); //true 출력
        })


    })

</script>
</head>
<body>

    A<input id = "my" type = "checkbox" name = "my" checked = "checked"><br>

    <button>OK</button>
</body>
</html>

toggle

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
.highlight {
    background : yellow;
}

</style>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function() {

        //toggle - on/off 설정
        //toggle은 오직 두가지 상태에서 상태를 전환하는 것
        $("p").on("click", function() {
            //css 주의
            console.log("!!!!!!!");
            $(this).toggleClass("highlight");

        })

    })
</script>
</head>
<body>

    <p class = "highlight">홍길동</p>

    <p>이순신</p>
    <p>유관순</p>

</body>
</html>

Manipulation

append , after

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
//append(context) 기존 text뒤에 새로운 내용 추가 html, 문자열, element 다 가능, 기존의 내용이 있을경우 이동됨
    $(function(){
        $("button").on("click", function(){
            $(".my").append($("<span>장군</span>")); //기존 내용 뒤에 추가
            $("<span>장군</span>").appendTo($(".my")); //context를 <to 위치>에 추가
            //$(".my").append($("h1")); //기존 태그의 이동
        })
    })
</script>
</head>
<body>
    <h1>영웅들</h1>
    <div>
        <div class="my">홍길동</div>
        <div class="my">이순신</div>
    </div>
    <button>ok</button>

</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    //요소의 뒤에 content를 추가 기존 content가 있을 경우 move됨
    //즉 div의 형제가 만들어짐, append의 경우 자식이 만들어짐
    $(function(){
        $("button").on("click", function(){
            $(".my").after($("<span>장군</span>"));
            //$("<span>장군</span>").insertAfter($(".my"));
            //$(".my").after($("h1"));
        })
    })
</script>
</head>
<body>
    <h1>영웅들</h1>
    <div>
        <div class="my">홍길동</div>
        <div class="my">이순신</div>
    </div>
    <button>ok</button>

</body>
</html>

prepend, before

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    //앞쪽에 html, 문자열 추가
    $(function(){
        $("button").on("click", function(){
            //$(".my").prepend($("<span>장군</span>"));
            //$("<span>장군</span>").prependTo($(".my"));
            $(".my").append($("h1"));
        })
    })
</script>
</head>
<body>
    <h1>영웅들</h1>
    <div>
        <div class="my">홍길동</div>
        <div class="my">이순신</div>
    </div>
    <button>ok</button>

</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    //요소의 앞에 삽입
    $(function(){
        $("button").on("click", function(){
            //$(".my").before($("<span>장군</span>"));
            //$("<span>장군</span>").insertBefore($(".my"));
            $(".my").before($("h1"));
        })
    })
</script>
</head>
<body>
    <h1>영웅들</h1>
    <div>
        <div class="my">홍길동</div>
        <div class="my">이순신</div>
    </div>
    <button>ok</button>

</body>
</html>

wrap

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    //선택 요소를 에워쌈, 한 요소마다 하나씩 에워쌈, append, prepend처럼 이동되지 않고 복사됨
    //wrapAll은 대상요소를 모두 한번에 에워쌈
    $(function(){
        $("button").on("click", function(){
            //$(".my").wrap("<div style = 'background : yellow' class = 'new'></div>"); //class = my 인것을 각각 요소로 에워쌈
            $(".my").wrapAll("<div style = 'background : yellow' class = 'new'></div>"); //하나로 감쌈

        })
    });
</script>
</head>
<body>
    <h1>영웅들</h1>
    <div>
        <div class="my">홍길동</div>
        <div class="my">이순신</div>    
    </div>
    <button>ok</button>

</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

<style type="text/css">
.new{
    border : 5px solid red;
}

</style>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

//선택된 요소를 감싼 부모를 제거
    $(function() {
        $("button").on("click", function(){
        if($(".my").parent().is(".new")){
            $(".my").unwrap();
        } else{
            $(".my").wrap("<div class = 'new'></div>");
        }
        })
    });
</script>
</head>
<body>
    <h1>영웅들</h1>
    <div>
        <div class="my">홍길동</div>
        <div class="my">이순신</div>
    </div>
    <p>xxxx</p>
    <div class="my">유관순</div>
    <button>toggle</button>

</body>
</html>

replaceWith

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">


    //기존 요소를 찾아서 새 요소로 변경, html문서에 content가 있을 경우에 타겟요소로 이동하여 변경됨
    $(function() {
        $("button").on("click", function(){
            $(".my1").replaceWith($(".my3")); //my1대신 my3 대입

        })
    });
</script>
</head>
<body>
    <h1>영웅들</h1>
    <div>
        <div class="my1">홍길동</div>
        <div class="my2">이순신</div>
        <div class="my3">유관순</div>
    </div>
    <button>toggle</button>


</body>
</html>

empty

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    //text를 포함한 자식(자손까지)요소의 제거
    $(function() {
        $("button").on("click", function(){
            $(".my1").empty();
        })
    });
</script>
</head>
<body>
    <h1>영웅들</h1>
    <div>
        <div class="my1">홍길동</div>
        <div class="my2">이순신</div>
        <div class="my3">유관순</div>

    </div>
    <div>
        <div class="inner first">테스트1</div>
        <div class="inner second">테스트2</div>
    </div>
    <button>toggle</button>


</body>
</html>

remove

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

<style type="text/css">

.new{
    border : 5px solid red;
}

.inner{
    color : red;
}

.my1{

    font-size:40px;
}

</style>

<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    //remove 일치하는 요소 제거
    $(function() {
        $("button").on("click", function(){
            //$(".my1").remove(); //my1제거
            $(".inner").remove(); //inner전부 제거
            //$(".inner").remove(".my1"); //my1 제거
        })
    });
</script>
</head>
<body>
    <h1>영웅들</h1>
    <div>
        <div class="inner my1">홍길동</div>
        <div class="inner my2">이순신</div>
        <div class="inner my3">유관순</div>
    </div>
    <button>toggle</button>

</body>
</html>

utility

each

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    $(function(){
        //$.each(idx, element)
        //데이터를 얻어 올 수 있으며 콜백함수내에서 반복을 빠지기 위해 false 사용
        //return 조건문
        //$.each(s, functoin(idx, ele))

        //1. 배열을 순회하며 출력 (가장 무난한 방법)
        var s = ["A", "B", "C", "D", "E"];
        for(var i=0; i<s.length;i++){
            console.log("1 >> ", s[i]);
        }

        //2. 배열을 each에 넘겨줌
        $.each(s, function(idx, data){
            console.log("2 >> ", data);
        })

        //3. Json
        var s2 = {"one" : 100, "two" : 200, "three" : 300};
        $.each(s2, function(key, value){
            console.log("3 json >> ", key,"\t" ,value);
        })

        var s3 = ["A", "B", "C", "D", "E"];
        $.each(s3, function(idx, data){
            console.log("s3 >>> " , idx, " ", data);
            return data != "C"; //data가 C가 되면 stop됨
        })


    })//end

</script>
</head>
<body>

</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    $(function(){
        var sum =0;

        $.each($("li"), function(idx, data){
            console.log(idx , "\t" , data);
            sum = sum + parseInt(data.innerText);
        })

        $("#result").text(sum);
    })//end

</script>
</head>
<body>
<ul>
   <li>100</li>
   <li>200</li>
   <li>300</li>
   <li>400</li>
  </ul>
    <span id="result"></span>

</body>
</html>

grep

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    $(function(){
        //$.grep(arr, function(element, idx), true/false) //
        //grep 필터링 처리 후 다시 배열로 반환(object, idx) 순서로 순서가 다름

        var s = ["A", "B", "C", "D"];
        var arr = $.grep(s, function(data, idx){ //순서가 다름
            return data =="B" //필터링 조건 - B제외 리턴
        }, true)//inverter //return 조건에 해당하는 것을 뺄것인가 넣을것인가
        //true 면 A C D 출력
        //false면 B 출력

        console.log(arr);


        var arr2 = $.grep(s, function(data, idx){
            return data =="B";
        }, false)

        console.log(arr2);
    })//end

</script>
</head>
<body>

</body>
</html>

map

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    $(function(){

        //$.map(arr, func) 배열을 가공해서 반환, 대소문자 변환, 값의 일부분을 반환
        var s = ["January", "February", "33333", "44444", "55555", "66666"];
        var arr = $.map(s, function(data, idx){
            console.log(data, idx);
            return data.substring(0, 3); // 문자열 3글자씩 
        })
        console.log(arr.join(","));

    })//end

</script>
</head>
<body>

</body>
</html>

merge

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    $(function(){

        //$.merge 두 배열이ㅡ 병합, 중복값이 있을시 덮어쓰지 않음 새로운 배열 생성
        var s = ["a", "b", "c"];
        var s1 = [1,2,3];
        var arr = $.merge(s1, s);

        console.log(arr);

    })//end

</script>
</head>
<body>

</body>
</html>

trim

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    $(function(){
        var s = "           hello          ";
        console.log(s.length); //26
        console.log($.trim(s).length); //5
    })//end

</script>
</head>
<body>

</body>
</html>

+ Recent posts