[jQuery] DOM 탐색과 조작

젼이·2025년 2월 8일

jQuery 정복하기

목록 보기
5/6

1. DOM 탐색과 조작이란?

DOM(Document Object Model)은 웹 페이지의 요소(HTML 태그)를 트리 구조로 표현한 것
-> jQuery를 사용하면 손쉽게 DOM 요소를 선택하고 조작할 수 있음

✅ DOM 탐색 (요소 찾기) -> parent(), children(), find(), siblings() 등
✅ DOM 조작 (요소 변경) -> text(), html(), val(), addClass(), removeClass() 등
✅ 이벤트 처리 -> click(), on()




2. jQuery를 활용한 DOM 탐색

jQuery는 DOM 트리에서 부모, 자식, 형제 요소를 쉽게 탐색할 수 있도록 메서드를 제공한다.


1. 부모 요소 찾기 (parent(), closest())

<div id="child">자식 요소</div>
<button id="findParent">부모 요소 찾기</button>
<p id="result"></p>

<script>
  	$(document).ready(function() {
  		$("#findParent").on("click", function() {
  			var parentElement = $("#child").parent().prop("tagName"); // 부모 요소의 태그명 가져오기
  			$("#result").text("부모 요소 태그: " + parentElement);
  		});
  	});
</script>
  • parent() -> 바로 위 부모 요소를 찾음
  • closest("태그") -> 특정한 부모 요소를 찾음

자식 요소 찾기 (children(), find())

<div id="container">
  	<p>첫 번째 단락</p>
  	<p>두 번째 단락</p>
</div>
<button id="getChildren">자식 요소 찾기</button>
<p id="output"><p>
  
<script>
  	$(document).ready(function() {
  		$("#getChildren").on("click", function() {
  			var childCount = $("#container").children("p".length;
  			$("#output").text("자식 요소 개수: " + childCount);
  		});
  	});
</script>
  • children("태그") -> 바로 아래 자식 요소 선택
  • find("태그") -> 자식뿐만 아니라 하위 요소 전체에서 특정 태그 찾기

형제 요소 찾기 (siblings(), next(), prev())

<ul>
    <li>첫 번째</li>
    <li class="selected">두 번째</li>
    <li>세 번째</li>
</ul>
<button id="findSiblings">형제 요소 찾기</button>
<p id="output"></p>

<script>
    $(document).ready(function() {
        $("#findSiblings").on("click", function() {
            var siblingsCount = $(".selected").siblings().length;
            $("#output").text("형제 요소 개수: " + siblingsCount);
        });
    });
</script>



3. jQuery를 사용한 DOM 조작

DOM을 조작하면 선택한 요소의 텍스트, HTML, 스타일을 변경할 수 있다.

1. 텍스트 및 HTML 조작(text(), html())

<p id="textContent">안녕하세요!</p>
<button id="changeText">텍스트 변경</button>
<button id="changeHtml">HTML 변경</button>

<script>
  	$(document).ready(function() {
  		$("#changeText").on("click", function() {
  			$("#textContent").text("변경된 텍스트");
  	
  		$("#changeHtml").on("click", function() {
  $("#textContent").html("<strong>HTML이 변경되었습니다!</strong>");
  
  		});
  	
  	});
</script>
  • text("값") -> 텍스트만 변경
  • html("값") -> HTML 태그 포함하여 변경 가능

2. 입력 필드 값 조작 (val())

<input type="text" id="username" placeholder="이름 입력">
<button id="getValue">값 가져오기</button>
<button id="setValue">값 변경</button>
<p id="output"></p>

<script>
    $(document).ready(function() {
        $("#getValue").on("click", function() {
            $("#output").text("입력된 값: " + $("#username").val());
        });

        $("#setValue").on("click", function() {
            $("#username").val("홍길동");
        });
    });
</script>
  • val() -> 입력 필드 값 가져오기 및 변경

3. 클래스 추가 및 제거(addClass(), removeClass())

<p id="text">스타일 변경 예제</p>
<button id="addStyle">스타일 추가</button>
<button id="removeStyle">스타일 제거<button>
  
<style>
  	.highlight { color: red; font-weight: bold; }
</style>

<script>
  	$(document).ready(function() {
  		$("#addStyle).on("click", function() {
  			$("#text").addClass("highlight");
  		});
  	
  		$("#removeStyle").on("click", function() {
  			$("#text").removeClass("highlight");
  		});
  	});
</script>
  • addClass("클래스명") -> CSS 클래스 추가
  • removeClass("클래스명") -> CSS 클래스 제거

4. 요소 추가 및 제거 (append(), prepend(), remove())

<ul id="list">
  <li>기존 항목 1</li>
  <li>기존 항목 2</li>
</ul>
<button id="addItem">항목 추가</button>
<button id="removeItem">항목 삭제<button>
  
<script>
  	$(document).ready(function() {
  		$("#addItem").on("click", function() {
  $("#list").append("<li>새로운 항목</li>")
  
  		$("#removeItem").on("click", function() {
            $("#list li:last").remove(); // 마지막 항목 삭제
        });
</script>
  • append("요소") -> 마지막에 추가
  • prepend("요소") -> 처음에 추가
  • remove() -> 요소 삭제
profile
신입 개발자 임니당 : > (2025.02.05~)

0개의 댓글