skip to Main Content

I have 2 tables with same class elements like:

<table class="myTbl">
<thead>
  <tr>
    <th>A</th>
    <th>B</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>1</td>
    <td>2</td>
  </tr>
</tbody>
 <table class="myTbl">
<thead>
  <tr>
    <th>C</th>
    <th>D</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>3</td>
    <td>4</td>
  </tr>
</tbody>

When I add jquery function like
$(function(){ $('.myTbl tbody').function() })

I want the function only run in specific table like table 1 , but I’m having duplicate classes. How to do it?

And I cant affect the html table like change class or add id,… cause It’s exported from other, only js or jquery to do it.

I tried $('.myTbl tbody:nth-child(1)') not working.

2

Answers


  1. you can do that with adding .eq(0) to your code

    $(document).ready(function(){
      $(".myTbl tbody").eq(0).click(function(){
        $(this).hide();
      });
    });
    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    </head>
    <body>
    
    <table class="myTbl">
    <thead>
      <tr>
        <th>C</th>
        <th>D</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>3</td>
        <td>4</td>
      </tr>
    </tbody>
    </table>
    
    <hr/>
    
    <table class="myTbl">
    <thead>
      <tr>
        <th>A</th>
        <th>B</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>2</td>
      </tr>
    </tbody>
    </table>
    
    </body>
    </html>
    Login or Signup to reply.
  2. You can add one more class to the element that you want to select, or you can also select by index of all selected elements.

      <!--Consider the following example: -->
    
        <p class="para">Paragraph1</p>
        <p class="para">Paragraph2</p>
        <p class="para">Paragraph3</p>
        <p class="para">Paragraph3</p>
        <script>
        const paragraphs = document.getElementByClassName("para");
        console.log(paragraphs[0]) //outputs the first paragraph
        console.log(paragraphs[1]) //outputs the second paragrah
        console.log(paragraphs[3]) //outputs the third paragraph
            //similarly you can select in jquery too
        </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search