웹사이트 검색

jQuery parent() 및 children() 트리 순회 함수 예제


jQuery는 부모, 자식, 형제, 이전 및 다음 요소를 가져오는 데 사용할 수 있는 많은 트리 순회 함수를 제공합니다. 우리는 각각의 jQuery 트리 순회 방법을 하나씩 살펴볼 것입니다. 오늘 우리는 두 가지 jQuery 순회 방법인 parent()children()을 살펴볼 것입니다.

jQuery를 부모() 함수

jQuery parent() 메서드는 선택한 HTML 요소의 직접 부모 요소를 가져오는 데 사용됩니다. 부모 요소가 반환되면 원하는 작업을 수행할 수 있습니다. 다음은 jQuery parent()를 사용하기 위한 구문입니다.

  • $ (자식).parent()

이것은 parent 요소의 직계 부모를 반환합니다.

  • &#36 (\자식\).parent("필터”)

필터는 parent() 메소드에 전달되는 선택적 매개변수입니다.

jQuery를 부모() 함수 예제

다음 예제는 parent() 메서드 사용법을 보여줍니다. jquery-parent.html

<!DOCTYPE html>
<html>
<head>
<title>jQuery Traversing Parent</title>

<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
<script>
$(document).ready(function(){
  $("h4").parent().css("background-color","yellow");
});
</script>
</head>
<body>

<span id="spanParent">Span Element - Parent of h4 element
<h4>This is an h4 element - child of Span.</h4>
</span>

</body>
</html>

jQuery를 자식() 함수

jQuery children() 메서드는 선택한 HTML 요소의 직접 자식을 가져오는 데 사용됩니다. children() 메서드를 사용하여 선택한 부모 요소의 자식 요소를 탐색할 수 있습니다. 이 방법을 사용하여 배경색 변경, 활성화, 비활성화, 숨기기, 표시 등과 같은 자식 요소에 원하는 작업을 수행할 수 있습니다. 다음은 jQuery children() 함수를 사용하기 위한 구문입니다.

  • $ (parentElement).children()

매개변수 없이 사용됩니다. 이것은 parentElement의 모든 직계 자식을 반환하는 데 사용됩니다.

  • $ (parentElement).children(childElement)

parentElementchildElement는 모든 HTML 요소가 될 수 있습니다. 그러면 parentElement와 일치하는 모든 childElement가 반환됩니다. 이 메서드의 childElement 매개 변수는 선택 사항이며 하위 요소를 가져오기 위한 추가 필터링 옵션을 제공합니다.

jQuery를 children() 함수 예제

다음 예제는 children() 메서드 사용법을 보여줍니다. jquery-children.html

<html>
<head>
<title>jQuery Traversing Children</title>

<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
<script>
$(document).ready(function(){
  //below code will run for all divs
  $("div").children("p").css("background-color","yellow");

   $("#spanParent").children("h4").css("background-color","green");
});
</script>
</head>
<body>

<div style="border:1px solid;">
<h3>h3 - Child of div</h3>
<p> p -Child of div</p>
<span> Span - Child of Div</span>
<p>Second p - Child of div</p>
</div>
<p> p element - Not a child of div</p>

<span id="spanParent">
<h4>This is an h4 element (child of Span).</h4>
</span>

</body>
</html>