development

요소가 부모의 자식인지 확인

big-blog 2020. 8. 3. 17:21
반응형

요소가 부모의 자식인지 확인


다음 코드가 있습니다.

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>

<div id="hello">Hello <div>Child-Of-Hello</div></div>
<br />
<div id="goodbye">Goodbye <div>Child-Of-Goodbye</div></div>

<script type="text/javascript">
<!--
function fun(evt) {
    var target = $(evt.target);    
    if ($('div#hello').parents(target).length) {
        alert('Your clicked element is having div#hello as parent');
    }
}
$(document).bind('click', fun);
-->
</script>

</html>

Child-Of-Hello클릭 할 때만 $('div#hello').parents(target).length> 0을 반환합니다.

그러나 어디서나 클릭 할 때마다 발생합니다.

내 코드에 문제가 있습니까?


다른 조상이 아닌 직접 부모에게만 관심이 있다면을 (를) 사용 parent()하고와 같이 셀렉터에게 줄 수 있습니다 target.parent('div#hello').

예 : http://jsfiddle.net/6BX9n/

function fun(evt) {
    var target = $(evt.target);    
    if (target.parent('div#hello').length) {
        alert('Your clicked element is having div#hello as parent');
    }
}

또는 일치하는 조상이 있는지 확인하려면을 사용하십시오 .parents().

예 : http://jsfiddle.net/6BX9n/1/

function fun(evt) {
    var target = $(evt.target);    
    if (target.parents('div#hello').length) {
        alert('Your clicked element is having div#hello as parent');
    }
}

.has()이 목적을 위해 설계된 것 같습니다. jQuery 객체를 반환하므로 다음 사항도 테스트해야합니다 .length.

if ($('div#hello').has(target).length) {
   alert('Target is a child of #hello');
}

특정 선택 기가없는 요소가 있고 다른 요소의 자손인지 여전히 확인하려는 경우 jQuery.contains ()

jQuery.contains (container, included)
설명 : DOM 요소가 다른 DOM 요소의 자손인지 확인하십시오.

부모 요소와 확인하려는 요소를 해당 함수에 전달하면 첫 번째 요소의 하위 요소 인 경우이를 반환합니다.


IE8 + 용 바닐라 1 라이너 :

parent !== child && parent.contains(child);

작동 방식은 다음과 같습니다.

function contains(parent, child) {
  return parent !== child && parent.contains(child);
}

var parentEl = document.querySelector('#parent'),
    childEl = document.querySelector('#child')
    
if (contains(parentEl, childEl)) {
  document.querySelector('#result').innerText = 'I confirm, that child is within parent el';
}

if (!contains(childEl, parentEl)) {
  document.querySelector('#result').innerText += ' and parent is not within child';
}
<div id="parent">
  <div>
    <table>
      <tr>
        <td><span id="child"></span></td>
      </tr>
    </table>
  </div>
</div>
<div id="result"></div>


대신 .closest ()를 사용하여 종료되었습니다.

$(document).on("click", function (event) {
    if($(event.target).closest(".CustomControllerMainDiv").length == 1)
    alert('element is a child of the custom controller')
});

두 용어를 바꾸면 코드가 작동합니다.

if ($(target).parents('div#hello').length) {

당신은 아이와 부모가 잘못된 길을 갔다.


다른 답변 외에도이 덜 알려진 방법을 사용하여 특정 부모의 요소를 가져올 수 있습니다.

$('child', 'parent');

귀하의 경우에는

if ($(event.target, 'div#hello')[0]) console.log(`${event.target.tagName} is an offspring of div#hello`);

Note the use of commas between the child and parent and their separate quotation marks. If they were surrounded by the same quotes

$('child, parent');

you'd have an object containing both objects, regardless of whether they exist in their document trees.

참고URL : https://stackoverflow.com/questions/3753634/check-if-an-element-is-a-child-of-a-parent

반응형