/contains Selector trong thư viện JQuery

contains Selector trong thư viện JQuery

Lựa chọn contains Selector là một trong các loại Selectors cơ bản được cung cấp sẵn trong thư viện jQuery được thiết kế để lựa chọn tất cả các phần tử chứa một chuỗi văn bản cụ thể.

1. Cú pháp

1.1. Thông tin chung

Contains Selector giúp chọn các phần tử mà chứa một chuỗi văn bản xác định, có thể xuất hiện trực tiếp trong phần tử được chọn, trong bất kỳ phần tử con nào của nó hoặc kết hợp cả hai.

Cú pháp:

$(":contains(text)")

Hoặc

jQuery(":contains(text)")

Tham số:

  • text: Chuỗi văn bản cần tìm kiếm. Nó là case-sensitive, nghĩa là phải giống chính xác từng ký tự.

Kết quả trả về:

  • Tất cả các phần tử mà chứa chuỗi văn bản được chỉ định.

Phiên bản hỗ trợ:

  • Được thêm vào phiên bản 1.1.4 của jQuery.

1.2. Một số lưu ý

Text trong ngữ cảnh của Contains Selector trong jQuery đề cập đến văn bản nằm trong các thẻ HTML. Tuy nhiên, cần nhấn mạnh rằng “text” không chỉ giới hạn trong phạm vi các thẻ HTML <text> mà bao gồm toàn bộ nội dung văn bản nằm trong các phần tử HTML.

Cụ thể, “text” có thể bao gồm:

  • Văn bản trực tiếp nằm trong các thẻ HTML, chẳng hạn

<p>Some text here</p>.

  • Văn bản nằm trong các phần tử con của một phần tử HTML,

<div> <p>This is a paragraph.</p> </div>

  • Kết hợp cả hai, ví dụ:

code<div> <p>This is some <span>nested text</span>.</p> </div>

Khi bạn sử dụng :contains('text') trong jQuery, nó sẽ tìm kiếm bất kỳ phần tử nào chứa chuỗi “text” trong nội dung của chúng (cả trực tiếp và các phần tử con).

contains Selector trong thư viện JQuery

2. Một số ví dụ

2.1. Game tìm chữ đơn giản với Contains Selector

Ví dụ dưới đây là một trò chơi đơn giản tìm từ trong một văn bản sử dụng Contains Selector.

<!DOCTYPE html>
<html>
<head>
  <title>Word Search Game</title>
  <style>
    .highlighted {
      background-color: yellow;
    }
  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
  <div>
    <p>This is a simple word search game using Contains Selector. Find the word "search".</p>
    <p>Try to find the word "word" as well.</p>
    <p>This game is a demonstration.</p>
	<p>Investing in <a href="https://cryptosall.net/tien-ma-hoa/"> cryptocurrencies </a> requires a solid understanding of the fundamentals. Understanding what <a href="https://cryptosall.net/tien-ma-hoa/"> cryptocurrency</a> are, 
	how <a href="https://cryptosall.net/blockchain-la-gi-va-lich-su-phat-trien-cua-blockchain/">blockchain</a> technology works, and the basics of different coins and tokens is crucial.</p>
    <p>Conducting thorough research and analysis of the <a href="https://cryptosall.net/tien-ma-hoa/">cryptocurreny</a> market is key. This includes studying historical price charts, 
	analyzing trends, and understanding market sentiment to make informed investment decisions. </p>
    <p>Managing risks is vital in <a href="https://cryptosall.net/tien-ma-hoa/">cryptocurrency</a> investing. Knowing how to assess and manage risks associated with volatile markets, 
	regulatory changes, and technological advancements is crucial to protect your investment. </p>
  </div>
  <input type="text" id="searchInput" placeholder="Enter word to search">
  <button id="findWordButton">Find Word</button>

  <script>
    $(document).ready(function() {
      $("#findWordButton").click(function() {
        var wordToFind = $("#searchInput").val().trim().toLowerCase();
        if (wordToFind === '') {
          alert('Please enter a word to search.');
          return;
        }

        // Loại bỏ bôi màu trước đó
        $('body').find('.highlighted').removeClass('highlighted');

        var elements = $('body').find(':contains("' + wordToFind + '")');

        // Bôi màu chỉ chữ được tìm thấy
        elements.html(function (_, html) {
          return html.replace(new RegExp('(' + wordToFind + ')', 'ig'), '<span class="highlighted">$1</span>');
        });
      });
    });
  </script>
</body>
</html>

2.2. Hàm filter có thể thực hiện tìm kiếm tương tự Contains Selector

Trong jQuery, hàm .filter() có thể được sử dụng để thực hiện tìm kiếm tương tự như :contains() selector. Hàm .filter() cho phép bạn chọn các phần tử dựa trên một hàm kiểm tra tùy chỉnh mà bạn tự định nghĩa.

Ví dụ dưới đây minh họa cách sử dụng .filter() để thực hiện tìm kiếm tương tự như :contains():

<!DOCTYPE html>
<html>
<head>
  <title>Custom Search Example</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
  <input type="text" id="searchInput" placeholder="Enter text to search">
  <div class="container">
    <p>This is a sample text containing the word "example".</p>
    <p>Another example of a sentence.</p>
    <p>This is some random text.</p>
  </div>

  <script>
    $(document).ready(function() {
      $("#searchInput").on("input", function() {
        var searchText = $(this).val().toLowerCase();
        $(".container p").removeClass("highlighted");

        if (searchText.length > 0) {
          $(".container p").filter(function() {
            return $(this).text().toLowerCase().includes(searchText);
          }).addClass("highlighted");
        }
      });
    });
  </script>

  <style>
    .highlighted {
      background-color: yellow;
    }
  </style>
</body>
</html>

Hàm .filter() có thể được tối ưu hóa và điều chỉnh linh hoạt hơn để thực hiện tìm kiếm tùy chỉnh, cho phép bạn xử lý các yêu cầu tìm kiếm phức tạp hơn dựa trên nội dung hoặc tiêu chí bạn định nghĩa.

Tuy nhiên, hiệu suất có thể không khác biệt rõ rệt so với sử dụng :contains() selector. Cách nào nhanh hơn sẽ phụ thuộc vào cách bạn tối ưu mã của mình và cách bạn xử lý tìm kiếm trong ứng dụng của mình.