Skip to main content

JQuery 탐색

parent()

  • 바로 직계 부모 요소 탐색
<article>
<span>Hello World!</span>
<div>
<p id="title">안녕하세요.</p>
<ul>
<li>1</li>
<li class="this">2</li>
<li>3</li>
</ul>
<button>클릭!</button>
</div>
<p><span>Bye~</span></p>
</article>
$("#title").parent().css("border", "1px solid skyblue");

image

parents()

  • 부모, 조상 요소 전부 탐색
<article>
<span>Hello World!</span>
<div>
<p id="title">안녕하세요.</p>
<ul>
<li>1</li>
<li class="this">2</li>
<li>3</li>
</ul>
<button>클릭!</button>
</div>
<p><span>Bye~</span></p>
</article>
$("li").parents().css("border", "1px solid red");

image

closest()

  • 가장 가까운 조상 요소 탐색
<article>
<span>Hello World!</span>
<div>
<p id="title">안녕하세요.</p>
<ul>
<li>1</li>
<li class="this">2</li>
<li>3</li>
</ul>
<button>클릭!</button>
</div>
<p>
<span><em>Bye~</em></span>
</p>
</article>
$("p").closest("div").css("background-color", "slateblue");

image

children()

  • 직계 자식 요소 탐색
<article>
<span>Hello World!</span>
<div>
<p id="title">안녕하세요.</p>
<ul>
<li>1</li>
<li class="this">2</li>
<li>3</li>
</ul>
<button>클릭!</button>
</div>
<p>
<span><em>Bye~</em></span>
</p>
</article>
$("div").children().css("border", "1px solid blue");

image

first() / last()

  • first(): 첫번째 요소를 지목
  • last(): 마지막 요소를 지목
<article>
<span>Hello World!</span>
<div>
<p id="title">안녕하세요.</p>
<ul>
<li>1</li>
<li class="this">2</li>
<li>3</li>
</ul>
<button>클릭!</button>
</div>
<p>
<span><em>Bye~</em></span>
</p>
</article>
$("article").children().first().css("border", "1px solid pink");
$("article").children().last().css("border", "1px solid red");

image

find()

  • 모든 하위 요소 탐색
<article>
<span>Hello World!</span>
<div>
<p id="title">안녕하세요.</p>
<ul>
<li>1</li>
<li class="this">2</li>
<li>3</li>
</ul>
<button class="this">클릭!</button>
</div>
<p>
<span><em>Bye~</em></span>
</p>
</article>
$("article").find(".this").css("border", "1px dashed gray");

image