-
[javascript] recursion, element.matches(selectorString), ~.함수이름 == -1이면 쓸 수 없는 함수인 것컴퓨터/JavaScript_typescript 2020. 1. 13. 09:24728x90
* recursion : when you call a function from within itself until or unless a condition is a met.
<div class="bg-1"> .bg-1 <div class="bg-2"> .bg-2 <div class="bg-3"> .bg-3 <div class="bg-4"> .bg-4 <div class="bg-5"> .bg-5 <div class="bg-6"> .bg-6 <div class="bg-7"> .bg-7 </div> </div> </div> </div> </div> </div> </div>
// distance : track the distance between our elem and an element with the selector var levelsUp = function (elem, selector, distance) { if (!distance) { distance = 0; } distance ++; // Get the parent of the current element var parent = elem.parentNode; // If you reach an element with no matches() method, bail if (!parent.matches) return -1; // If we've reached the parent, return the distance if (parent.matches(selector)) return distance; // Otherwise, recursively run levelsUp() again // The levelsUp() method will run multiple times until it finds a match or hits the window element. // and will return whatever the final value for distance is (or -1 if no match is found) return levelsUp(parent, selector, distance); }
var start = document.querySelector('.bg-7'); console.log(levelsUp(start, '.bg-5')); // 2 console.log(levelsUp(start, '.bg-1')); // 6 console.log(levelsUp(start, '.bg-3')); // 4 console.log(levelsUp(start, '.nope')); // -1
var result = element.matches(selectorString)
source : Chris Ferdinandi, go make things
https://developer.mozilla.org/en-US/docs/Web/API/Element/matches
반응형'컴퓨터 > JavaScript_typescript' 카테고리의 다른 글
throw Error (0) 2020.01.19 Template, Tagged Template literals, 함수이름`HTML내용` (0) 2020.01.19 API(Application Programming Interface) (0) 2020.01.07 메서드 (0) 2020.01.03 javascript 함수 3 (0) 2019.11.18