[jQuery] 엘리먼트 제어

형이·2023년 8월 21일

jQuery

목록 보기
9/14
post-thumbnail

📝 jQuery

🖥️ 1. 엘리먼트 제어

참고 링크 1
참고 링크 2

1-1. 자식으로 삽입

append(), appendTo(), html(), prepend(), prependTo(), text()

1-2. 형제로 삽입

after(), before(), insertAfter(), insertBefore()

1-3. 부모로 감싸기

unwrap(), wrap(), wrapAll(), wrapInner()

1-4. 삭제

detach(), empty(), remove(), unwrap()

1-5. 치환

참고 링크 3
replaceAll(), replaceWith()

1-6. 클래스

addClass(), hasClass(), removeClass(), toggleClass()

1-7. 속성제어

val()


📝 예제

EX) append

	<head>
    ...
    <script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
    <style>
        p{ background: tomato; }
    </style>
</head>
<body>
    <p id="user_p">jQuery는 : </p>
    <script>
        $('p').append("<strong>재미있다</strong>");

        // document.getElementById("user_p").innerHTML=document.getElementById("user_p").textContent + "<strong>재미있다</strong>";
    </script>
</body>

EX2) after
	
    <head>
    ...
    <script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
    <p>jQuery는 : </p>
    <script>
        $("p").after("<strong>재미있다</strong>")
    </script>
</body>

EX) wrap

	<head>
    ...
    <script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
    <style>
        div {
            border:2px blue solid;
            margin:2px;
            padding:2px;
        }
        p {
            background:yellow;
            margin:2px;
            padding:2px;
        }
        strong {
            color:red;
        }
    </style>
</head>
<body>
    <span>Span Text</span>
    <strong>What about me?</strong>
    <span>Another one</span>
    <script>
        $("span").wrap("<div><div><p><em>  </em></p></div></div>")
    </script>
</body>

EX) remove
	
    <head>
    ...
    <script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
    <style>
        p{ background: tomato; margin: 6px 0; }
    </style>
</head>
<body>
    <p>Hello</p>
    how are
    <p> you?</p>
    <button>call remove() </button>
    <script>
        $("button").click(function(){
            $("p").remove();
        });
    </script>
</body>

EX) replace
	
    <head>
    ...
    <script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
    <style>
        p{ background: powderblue; margin: 6px 0; }
    </style>
</head>
<body>
    <p>Hello</p>  
    <p>JavaScript</p>  
    <p>World</p>
    <script>
        $("<b>jQuery</b>").replaceAll("p");
    </script>
</body>

0개의 댓글