순수 자바스크립트로 상위요소 찾는 코드입니다.
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개
게시글 목록
| 번호 | 제목 |
|---|---|
| 16619 | |
| 16618 | |
| 16612 | |
| 16603 | |
| 16598 | |
| 16589 | |
| 16578 | |
| 16571 | |
| 16563 | |
| 16554 | |
| 16546 | |
| 16534 | |
| 16527 | |
| 16520 | |
| 16513 | |
| 16510 | |
| 16505 | |
| 16498 | |
| 16490 | |
| 16486 | |
| 16482 | |
| 16465 | |
| 16458 | |
| 16456 | |
| 16448 | |
| 16447 |
PHP
한글 초,중,종성 분리하기
3
|
| 16440 | |
| 16439 |
웹서버
nginx 설치시 보안
3
|
| 16438 | |
| 16430 |
댓글 작성
댓글을 작성하시려면 로그인이 필요합니다.
로그인하기