skip to Main Content

I have this html:

<td class="catName" data-bs-toggle="collapse" data-bs-target=".category1">A</td>
<td class="catName" data-bs-toggle="collapse" data-bs-target=".category2">B</td>
<td class="catName" data-bs-toggle="collapse" data-bs-target=".category3">C</td>

I want to use the filter function to find the class that has the innerText "A".

Trying with:

jQuery(".catName").filter(item => jQuery(item).text() == "A");

But it doesn’t work.

I am using Jquery. I have to use filter. And I have to use an arrow function.

2

Answers


    1. Due to your markup being invalid stands nothing will work. You need to add some corresponding table elements.

    2. The first argument of filter is index, and item is the second argument (which is the opposite way native JS array methods work).

    In this example I’m filtering the cell with "A" and turning its background red.

    $(".catName").filter((index, item) => {
      return $(item).text() == "A";
    }).css('background-color', 'red');
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table>
      <tbody>
        <tr>
          <td class="catName" data-bs-toggle="collapse" data-bs-target=".category1">A</td>
          <td class="catName" data-bs-toggle="collapse" data-bs-target=".category2">B</td>
          <td class="catName" data-bs-toggle="collapse" data-bs-target=".category3">C</td>
        </tr>
      </tbody>
    </table>
    Login or Signup to reply.
  1. At a minimum <td> elements need to be wrapped inside <table> element tags for it to make sense to the DOM.

    The other thing you need to change is that the JQuery filter() methods receives the index first, and the JQuery item as the second argument. So you need filter((i, item) =>

    $(".catName").filter((i, item) => $(item).text() == "A");

    See JSFiddle for full example:
    https://jsfiddle.net/Lexdp7rt/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search