상위요소 찾기 노드
순수 자바스크립트로 상위요소 찾는 코드입니다.
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에서 해주시기 바랍니다.
| 번호 | 분류 | 제목 | 글쓴이 | 날짜 | 조회 |
|---|---|---|---|---|---|
| 4886 | PHP | 7년 전 | 2383 | ||
| 4885 | PHP | 7년 전 | 2702 | ||
| 4884 | 기타 | 7년 전 | 3080 | ||
| 4883 | PHP | 7년 전 | 2360 | ||
| 4882 | PHP | 7년 전 | 3698 | ||
| 4881 | PHP | 7년 전 | 3337 | ||
| 4880 | JavaScript | 7년 전 | 3339 | ||
| 4879 | JavaScript | 7년 전 | 3060 | ||
| 4878 | PHP | 7년 전 | 5449 | ||
| 4877 | PHP |
welcome
|
7년 전 | 2907 | |
| 4876 | OS | 7년 전 | 2932 | ||
| 4875 | 기타 | 7년 전 | 2383 | ||
| 4874 | PHP |
|
7년 전 | 2748 | |
| 4873 | 웹서버 |
black
|
7년 전 | 2353 | |
| 4872 | PHP |
|
7년 전 | 3569 | |
| 4871 | 기타 | 7년 전 | 3350 | ||
| 4870 | 기타 | 7년 전 | 5650 | ||
| 4869 | 기타 | 7년 전 | 4215 | ||
| 4868 | JavaScript | 7년 전 | 4579 | ||
| 4867 | PHP |
|
7년 전 | 3918 | |
| 4866 | JavaScript | 7년 전 | 4438 | ||
| 4865 | PHP | 7년 전 | 5625 | ||
| 4864 | jQuery | 7년 전 | 2586 | ||
| 4863 | jQuery |
루돌프사슴코
|
7년 전 | 3990 | |
| 4862 | JavaScript | 7년 전 | 7799 | ||
| 4861 | 기타 | 7년 전 | 2255 | ||
| 4860 | 웹서버 | 7년 전 | 2499 | ||
| 4859 | 기타 | 7년 전 | 6951 | ||
| 4858 | 기타 | 7년 전 | 5114 | ||
| 4857 | 웹서버 | 7년 전 | 6190 |
댓글 작성
댓글을 작성하시려면 로그인이 필요합니다.
로그인하기