IT

내용과 정확히 일치하는 요소를 선택하십시오.

lottoking 2020. 6. 15. 08:06
반응형

내용과 정확히 일치하는 요소를 선택하십시오.


좋아, :contains()jQuery의 선택기 가 입력 된 문자열 있는 요소를 선택 하는 방법이 있는지 궁금합니다 .

예를 들어-

<p>hello</p>
<p>hello world</p>

$('p:contains("hello")').css('font-weight', 'bold');

선택기는 두 p요소를 모두 선택 하고 굵게 표시하지만 첫 번째 요소 만 선택하고 싶습니다.


아니요,이를 수행하는 jQuery (또는 CSS) 선택기가 없습니다.

당신은 쉽게 사용할 수 있습니다 filter:

$("p").filter(function() {
    return $(this).text() === "hello";
}).css("font-weight", "bold");

그것은 아니다 선택 ,하지만 일을한다. :-)

"hello"전후에 공백을 처리하려면 여기에 공백을 넣을 수 있습니다 $.trim.

return $.trim($(this).text()) === "hello";

거기 조기 최적화를 위해, 당신은 일치하지 않음을 걱정하지 않는 경우 <p><span>hello</span></p>와 유사한, 당신에 대한 호출 피할 수 $text사용하여 innerHTML직접 :

return this.innerHTML === "hello";

...하지만 당신은해야 할 것 많은 이 문제에 대한 당신은 아마 첫번째 다른 문제가있을 거라고 많은, 단락을. :-)


의사 확장 기능을 추가하십시오.

$.expr[':'].textEquals = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return $(elem).text().match("^" + arg + "$");
    };
});

그럼 당신은 할 수 있습니다 :

$('p:textEquals("Hello World")');

따라서 Amandu의 대답은 대부분 작동합니다. 그러나 야생에서 그것을 사용하면서, 나는 발견 될 것으로 예상되는 것들이 발견되지 않는 몇 가지 문제에 부딪쳤다. 때로는 요소의 텍스트 주위에 임의의 공백이 있기 때문입니다. "Hello World"를 검색하는 경우 여전히 "Hello World"또는 "Hello World \ n"과 일치 시키려고한다고 생각합니다. 따라서 방금 공백을 제거하는 "trim ()"메서드를 함수에 추가하고 더 잘 작동하기 시작했습니다.

구체적으로 특별히...

$.expr[':'].textEquals = function(el, i, m) {
    var searchText = m[3];
    var match = $(el).text().trim().match("^" + searchText + "$")
    return match && match.length > 0;
}

또한이 답변은 텍스트로 링크 선택 (정확히 일치) 과 매우 유사합니다.

그리고 보조 메모 ... 는 검색된 텍스트 전후trim공백 만 제거 합니다. 단어 중간에 공백이 제거되지 않습니다. 나는 이것이 바람직한 행동이라고 생각하지만 원하는 경우 변경할 수 있습니다.


jQuery의 filter () 함수를 사용하여이를 달성 할 수 있습니다 .

$("p").filter(function() {
// Matches exact string   
return $(this).text() === "Hello World";
}).css("font-weight", "bold");

나는 나에게 맞는 방법을 찾았다. 100 % 정확하지는 않지만 개별 공백을 포함하지 않는 문자열을 확인하기 때문에 찾고있는 단어 이상을 포함하는 모든 문자열을 제거합니다. 그건 그렇고 당신은 이러한 ""이 필요하지 않습니다. jQuery는 문자열을 찾고 있다는 것을 알고 있습니다. : contains () 부분에 공백이 하나만 있는지 확인하십시오. 그렇지 않으면 작동하지 않습니다.

<p>hello</p>
<p>hello world</p>
$('p:contains(hello):not(:contains( ))').css('font-weight', 'bold');

그리고 네, 같은 물건이 있으면 작동하지 않는다는 것을 알고 있습니다 <p>helloworld</p>


Like T.J. Crowder stated above, the filter function does wonders. It wasn't working for me in my specific case. I needed to search multiple tables and their respective td tags inside a div (in this case a jQuery dialog).

$("#MyJqueryDialog table tr td").filter(function () {
    // The following implies that there is some text inside the td tag.
    if ($.trim($(this).text()) == "Hello World!") {
       // Perform specific task.
    }
});

I hope this is helpful to someone!


An one-liner that works with alternative libraries to jQuery:

$('p').filter((i, p) => $(p).text().trim() === "hello").css('font-weight', 'bold');

And this is the equivalent to a jQuery's a:contains("pattern") selector:

var res = $('a').filter((i, a) => $(a).text().match(/pattern/));

The .first() will help here

$('p:contains("hello")').first().css('font-weight', 'bold');

참고URL : https://stackoverflow.com/questions/15364298/select-element-by-exact-match-of-its-content

반응형