[jquery] jQuery : 텍스트로 요소 찾기

누구든지 id 또는 클래스가 아닌 내용을 기반으로 요소를 찾을 수 있는지 말해 줄 수 있습니까 ?

고유 한 클래스 또는 ID가없는 요소를 찾으려고합니다. 그런 다음 해당 요소의 부모를 찾아야합니다.



답변

:contains선택기를 사용하여 내용을 기반으로 요소를 가져올 수 있습니다 .

여기 데모

$('div:contains("test")').css('background-color', 'red');
<div>This is a test</div>
<div>Another Div</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>


답변

jQuery 문서에서는 다음과 같이 말합니다.

일치하는 텍스트는 선택한 요소, 해당 요소의 자손 또는 조합에서 직접 나타날 수 있습니다

따라서 :contains() selector 를 사용하는 것만으로는 충분하지 않으며 , 검색하는 텍스트 가 대상 요소 의 직접 컨텐츠 인지 확인해야 합니다.

function findElementByText(text) {
    var jSpot = $("b:contains(" + text + ")")
                .filter(function() { return $(this).children().length === 0;})
                .parent();  // because you asked the parent of that element

    return jSpot;
}


답변

Fellas, 나는 이것이 오래되었다는 것을 알고 있지만, 나는이 솔루션을 모두보다 잘 작동한다고 생각합니다. 우선 jquery : contains ()가 제공되는 대소 문자 구분을 극복하십시오.

var text = "text";

var search = $( "ul li label" ).filter( function ()
{
    return $( this ).text().toLowerCase().indexOf( text.toLowerCase() ) >= 0;
}).first(); // Returns the first element that matches the text. You can return the last one with .last()

가까운 장래에 누군가 도움이 되길 바랍니다.


답변

로켓의 대답이 작동하지 않습니다.

<div>hhhhhh
<div>This is a test</div>
<div>Another Div</div>
</div>

여기서 간단히 그의 데모 를 수정 하면 루트 DOM이 선택되었음을 알 수 있습니다.

$('div:contains("test"):last').css('background-color', 'red');

이 문제를 해결하려면 코드 에 ” : last “선택기를 추가 하십시오.


답변

내 의견으로는 가장 좋은 방법입니다.

$.fn.findByContentText = function (text) {
    return $(this).contents().filter(function () {
        return $(this).text().trim() == text.trim();
    });
};


답변

예, jQuery contains선택기를 사용하십시오 .


답변

다음 jQuery는 텍스트를 포함하지만 자식이없는 div 노드 (DOM 트리의 리프 노드)를 선택합니다.

$('div:contains("test"):not(:has(*))').css('background-color', 'red');
<div>div1
<div>This is a test, nested in div1</div>
<div>Nested in div1<div>
</div>
<div>div2 test
<div>This is another test, nested in div2</div>
<div>Nested in div2</div>
</div>
<div>
div3
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>