programing

jQuery를 사용하여 div에 특정 클래스의 자식이 있는지 확인

lastcode 2023. 8. 25. 23:42
반응형

jQuery를 사용하여 div에 특정 클래스의 자식이 있는지 확인

나는 디브가 있습니다.#popup클래스와 함께 여러 문단으로 동적으로 채워지는.filled-text저는 jQuery가 제게 알려주도록 하려고 합니다.#popup다음 단락 중 하나가 들어 있습니다.

다음 코드가 있습니다.

$("#text-field").keydown(function(event) {
    if($('#popup').has('p.filled-text')) {
        console.log("Found");
     }
});

좋은 의견이라도 있나?

찾기 기능을 사용할 수 있습니다.

if($('#popup').find('p.filled-text').length !== 0)
   // Do Stuff

hasClass 함수가 있습니다.

if($('#popup p').hasClass('filled-text'))

jQuery의 자식 함수를 사용합니다.

$("#text-field").keydown(function(event) {
    if($('#popup').children('p.filled-text').length > 0) {
        console.log("Found");
     }
});

$.children('').length선택기와 일치하는 하위 요소의 개수를 반환합니다.

심플 웨이

if ($('#text-field > p.filled-text').length != 0)

같은 클래스를 가진 여러 개의 div가 있고 일부 div만 해당 클래스를 가진 경우 각 div를 확인해야 합니다.

            $('.popup').each(function() {
                if ($(this).find('p.filled-text').length !== 0) {
                    $(this).addClass('this-popup-has-filled-text');
                }
            });

만약 그것이 직접적인 아이라면, 그것이 더 깊게 중첩될 수 있다면 당신은 아래와 같이 할 수 있습니다 >

$("#text-field").keydown(function(event) {
    if($('#popup>p.filled-text').length !== 0) {
        console.log("Found");
     }
});

당신이 이 질문을 한 이후 10년 동안 jQuery는 거의 정확하게 다음을 추가했습니다..has(위에서 설명한 함수입니다.호출된 선택기를 필터링합니다. 사용하는 것보다 빠릅니다.$('.child').parent('.parent')그리고 잠재적으로 DOM을 따라 올라갑니다.

$("#text-field").keydown(function(event) {
    if($('#popup').has('p.filled-text').length) {
        console.log("Found");
    }
});

$('.classone')

  • .find('p .classtwo')하위 요소 제공=p
  • .has('p .classtwo').classone' 요소를 지정합니다.

여기 그것을 하는 좋은 방법이 있습니다.

if($("#your_id .your_class")) { 
   //Do something
});

(.your_class")가 부모("#your_id")의 유일한 자식 또는 부모("#your_id")의 첫 번째 자식인 경우에도 ">"를 사용할 수 있습니다.

if($("#your_id>.your_class")) { 
   //Do something
});

("#your_id")는 부모 클래스 또는 ID입니다.
(."your_class")는 찾으려는 클래스 또는 ID입니다.

언급URL : https://stackoverflow.com/questions/10539162/using-jquery-to-see-if-a-div-has-a-child-with-a-certain-class

반응형