상위요소 찾기 노드
순수 자바스크립트로 상위요소 찾는 코드입니다.
jquery로 하면 쉽게할 수 있지만 그렇지 못한 환경에서는
이러한 코드가 필요할 수 있습니다.
그래서 소스코드 공유합니다.
[code]
<html>
<head>
</head>
<body>
<div class="parent_node">
<div id="my_elm">test</div>
</div>
<script>
function collectionHas(a, b) { //helper function (see below)
for(var i = 0, len = a.length; i < len; i ++) {
if(a[i] == b) return true;
}
return false;
}
function findParentBySelector(elm, selector) {
var all = document.querySelectorAll(selector);
var cur = elm.parentNode;
while(cur && !collectionHas(all, cur)) { //keep going up until you find a match
cur = cur.parentNode; //go up
}
return cur; //will return null if not found
}
var my_elm = document.getElementById("my_elm"); //
var selector = ".parent_node";
var parent = findParentBySelector(my_elm, selector);
console.log(parent);
</script>
</body>
</html>
[/code]
댓글 3개
게시판 목록
개발자팁
질문은 QA에서 해주시기 바랍니다.
| 번호 | 분류 | 제목 | 글쓴이 | 날짜 | 조회 |
|---|---|---|---|---|---|
| 5036 | 웹서버 | 4년 전 | 2137 | ||
| 5035 | 웹서버 | 4년 전 | 2165 | ||
| 5034 | 웹서버 | 4년 전 | 2397 | ||
| 5033 | 웹서버 | 4년 전 | 1776 | ||
| 5032 | 웹서버 | 4년 전 | 2131 | ||
| 5031 | 웹서버 | 4년 전 | 2511 | ||
| 5030 | MySQL | 4년 전 | 2880 | ||
| 5029 | 웹서버 | 4년 전 | 7174 | ||
| 5028 | 웹서버 |
kerimdoor
|
4년 전 | 1628 | |
| 5027 | OS | 4년 전 | 6548 | ||
| 5026 | PHP |
|
4년 전 | 4636 | |
| 5025 | JavaScript |
|
4년 전 | 2400 | |
| 5024 | MySQL |
|
4년 전 | 3810 | |
| 5023 | MySQL | 4년 전 | 3027 | ||
| 5022 | PHP | 4년 전 | 2319 | ||
| 5021 | PHP |
|
4년 전 | 3246 | |
| 5020 | PHP | 4년 전 | 4301 | ||
| 5019 | PHP | 5년 전 | 4324 | ||
| 5018 | 웹서버 | 5년 전 | 6700 | ||
| 5017 | 기타 |
HappyTank
|
5년 전 | 5066 | |
| 5016 | MySQL | 5년 전 | 3080 | ||
| 5015 | 기타 | 5년 전 | 2268 | ||
| 5014 | 기타 | 5년 전 | 2831 | ||
| 5013 | 기타 | 5년 전 | 2250 | ||
| 5012 | 기타 | 5년 전 | 2258 | ||
| 5011 | 기타 | 5년 전 | 2211 | ||
| 5010 | 기타 | 5년 전 | 1770 | ||
| 5009 | 기타 | 5년 전 | 2377 | ||
| 5008 | 기타 | 5년 전 | 2007 | ||
| 5007 | 기타 | 5년 전 | 1971 |
댓글 작성
댓글을 작성하시려면 로그인이 필요합니다.
로그인하기