programing

jQuery로 텍스트 콘텐츠로 요소를 찾으려면 어떻게 해야 합니까?

instargram 2023. 5. 17. 22:27
반응형

jQuery로 텍스트 콘텐츠로 요소를 찾으려면 어떻게 해야 합니까?

ID나 클래스가 아닌 내용으로 요소를 찾는 것이 가능한지 알려주실 수 있나요?

클래스나 ID가 다른 요소를 찾으려고 합니다. (그러면 해당 요소의 부모를 찾아야 합니다.)

선택기를 사용하여 내용에 따라 요소를 가져올 수 있습니다.

여기서 데모

$('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() 선택기, 검색하는 텍스트가 대상 요소의 직접 내용인지 확인해야 합니다. 다음과 같은 작업을 수행할 수 있습니다.

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

친구들, 나는 이것이 오래된 것이라는 것을 알지만 이봐, 나는 모든 것보다 더 잘 작동한다고 생각하는 이 해결책을 가지고 있어요.무엇보다도 먼저 jquery:()에 포함된 대/소문자 구분을 극복합니다.

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" 선택기를 추가하여 이 문제를 해결합니다.

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

$('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>

제 생각에는 최선의 방법입니다.

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

예, jQuery 선택기를 사용합니다.

지금까지의 모든 답변이 특정 텍스트를 포함하는 직접 자식 텍스트 노드를 포함하는 특정 요소일치하지 않습니다.

다음 예를 생각해 보십시오.우리는 모든 호빗, 즉, 모두를 찾고 싶습니다.divs는 "sysbit"(단어 테두리 포함, 대소문자 무시) 단어를 포함하는 직접 자식 텍스트 노드를 포함합니다.

$(function() {
    
    const ELEMTYPE = Node.ELEMENT_NODE
    const TEXTTYPE = Node.TEXT_NODE
    
    /*
    Behaves a bit like Python's os.walk().
    The `topdown` parameter is not strictly necessary for this example.
    */
    function* walk_text(root, topdown=true) {
        const childs = []
        const textchilds = []
        for (const child of root.childNodes) {
            const childtype = child.nodeType
            if (childtype === ELEMTYPE) {
                childs.push(child)
            } else if (childtype === TEXTTYPE) {
                textchilds.push(child)
            }
        }
        if (topdown) {
            yield [root, textchilds]
        }
        for (const child of childs) {
            yield* walk_text(child, topdown)
        }
        if (!topdown) {
            yield [root, textchilds]
        }
    }
    
    function* walk_matching(startnode, nodepat, textpat) {
        for ( [elem, textchilds] of walk_text(startnode) ) {
            if ( nodepat.test(elem.nodeName) ) {
                for ( const textchild of textchilds ) {
                    if ( textpat.test(textchild.nodeValue) ) {
                        yield elem
                        break
                    }
                }
            }
        }
    }
    
    // raw dom node
    let startnode = $('body')[0]
    
    // search for element nodes with names matching this pattern ...
    let nodepat = /^div$/i
    
    // ... containing direct child text nodes matching this pattern
    let textpat = /\bhobbit\b/i
    
    for ( const node of walk_matching( startnode, nodepat, textpat ) ) {
        $(node).css({
            border: '1px solid black',
            color: 'black'
        })
    }

});
div {
    margin:10px 0;
    padding: 10px;
    border: 1px solid silver;
    color: silver;
    font-style:italic;
}

div:before {
    display:block;
    content: attr(name);
    font-style:normal;
}

/* Inserted by SO, we are not interested in it */
body + div {
    display: none;
}
<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Find the hobbits</title>
    </head>
    <body>
        <div name='Tolkien'>
            book writer
            <div name='Elrond'>
                elven king
                <div name='Arwen'>elven princess</div>
                <div name='Aragorn'>human king, son-in-law</div>
            </div>
            <div name='Gandalf'>
                wizard, expert for hobbits
                <div name='Bilbo'>
                    old hobbit
                    <div name='Frodo'>
                        young hobbit
                        <div name='Samweis'>best friend hobbit</div>
                    </div>
                </div>
                <div name='Gollum'>ex hobbit</div>
                <div name='Odo'>hobbit</div>
            </div>
        </div>
        <script src= "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    </body>
</html>

다른 답변은 다음을 찾습니다('호빗'을 검색할 때).

  • Rocket Hazmat의 대답:톨킨, 간달프, 빌보, 프로도, 샘웨이스, 골룸, 오도
  • Morgs의 대답:톨킨
  • 요압 바네아의 대답: 간달프, 프로도.
  • Nicholas Sushkin의 대답: Samweis, Golum, Odo.
  • Rocket Hazmat의 댓글 답변, Terry Lin의 답변, rplaurindo의 답변:오도

여러분이 무엇을 하고 싶은지에 따라, 이 모든 대답은 이치에 맞습니다.Rocket Hazmat의 답변, Morgs의 답변 및 Terry Lin의 답변이 부분적으로 내 해결책보다 2배 이상 빠르게 수행되기 때문에 현명하게 선택하십시오.그것은 그들이 전체 DOM을 통과할 필요가 없기 때문이라고 생각합니다.사용하는 대부분의 응답자.filter()매우 빠른 속도로 공연합니다.

언급URL : https://stackoverflow.com/questions/7321896/how-can-i-find-elements-by-text-content-with-jquery

반응형