closest

z6su3Β·2022λ…„ 3μ›” 31일
0

JavaScript

λͺ©λ‘ 보기
5/6

πŸ‡ What is closest ❓

κΈ°μ€€ Elementμ—μ„œ closest() λ©”μ†Œλ“œλ₯Ό 톡해 μžμ‹ λΆ€ν„° λΆ€λͺ¨μš”μ†Œ λ‹¨μœ„λ‘œ μΆœλ°œν•˜μ—¬ 각 μš”μ†Œκ°€ μ§€μ •ν•œ μ„ νƒμžμ— λ§Œμ‘±ν•  λ•ŒκΉŒμ§€ λ¬Έμ„œ 루트λ₯Ό νƒμƒ‰ν•œλ‹€. 이 쀑 κ°€μž₯ κ°€κΉκ²Œ 쑰건에 λ§Œμ‘±ν•œ λΆ€λͺ¨ μš”μ†Œκ°€ λ°˜ν™˜λ˜λ©°, 쑰건에 λ§Œμ‘±ν•œ μš”μ†Œκ°€ μ—†μœΌλ©΄ null을 λ°˜ν™˜ν•œλ‹€.

πŸ‡ μ‚¬μš©λ°©λ²•

πŸ₯• Syntax

var closestElement = targetElement.closest(selector);

πŸ₯• Example

<article>
  <div id="div-01">Here is div-01
    <div id="div-02">Here is div-02
      <div id="div-03">Here is div-03</div>
    </div>
  </div>
</article>

var el = document.getElementById('div-03');

var r1 = el.closest("#div-02");
// id=div-02 쑰건이 λ§Œμ‘±ν•˜λ―€λ‘œ 속성을 가진 λΆ€λͺ¨ μš”μ†Œκ°€ λ°˜ν™˜λœλ‹€.

var r2 = el.closest("div div");
// div μš”μ†Œμ— λ§Œμ‘±ν•œ μš”μ†Œ 쀑 div μžμ‹μ„ κ°€λ¦¬ν‚€λ―€λ‘œ, id=div-03 μžμ‹ μ΄ λ§Œμ‘±λœλ‹€.

var r3 = el.closest("article > div");
// κ°€μž₯ κ°€κΉŒμš΄ article μš”μ†Œ λ°”λ‘œ ν•˜μœ„μ˜ div μš”μ†Œ id=div-01 속성을 가진 μš”μ†Œκ°€ λ°˜ν™˜λœλ‹€.

var r4 = el.closest(":not(div)");
// div μš”μ†Œκ°€ μ•„λ‹Œ κ°€μž₯ κ°€κΉŒμš΄ λΆ€λͺ¨ article μš”μ†Œκ°€ λ°˜ν™˜λœλ‹€.
profile
기얡은 기둝을 이길수 μ—†λ‹€

0개의 λŒ“κΈ€