Home > Mobile >  How to get specific class element of table?(duplicate class)
How to get specific class element of table?(duplicate class)

Time:10-05

I have 2 tables with same class elements like:

<table >
<thead>
  <tr>
    <th>A</th>
    <th>B</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>1</td>
    <td>2</td>
  </tr>
</tbody>
 <table >
<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.

CodePudding user response:

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 >
<thead>
  <tr>
    <th>C</th>
    <th>D</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>3</td>
    <td>4</td>
  </tr>
</tbody>
</table>

<hr/>

<table >
<thead>
  <tr>
    <th>A</th>
    <th>B</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>1</td>
    <td>2</td>
  </tr>
</tbody>
</table>

</body>
</html>

CodePudding user response:

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 >Paragraph1</p>
    <p >Paragraph2</p>
    <p >Paragraph3</p>
    <p >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>
  • Related