[javascript] 요소가 부모의 자식인지 확인

다음 코드가 있습니다.

<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');
}


답변

IE8 + 용 Vanilla 1-liner :

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>


답변

특정 선택자가없는 요소가 있고 여전히 다른 요소의 하위 요소인지 확인하려면 jQuery.contains ()를 사용할 수 있습니다.

jQuery.contains (container, included)
설명 : DOM 요소가 다른 DOM 요소의 자손인지 확인합니다.

부모 요소와 확인하려는 요소를 해당 함수에 전달할 수 있으며 후자가 첫 번째의 후손이면 반환됩니다.


답변

대신 .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`);

자식과 부모 사이에 쉼표를 사용하고 별도의 따옴표를 사용합니다. 같은 따옴표로 묶인 경우

$('child, parent');

문서 트리에 존재하는지 여부에 관계없이 두 개체를 모두 포함하는 개체가 있습니다.