Home > Software engineering >  How to select a classes with same name without using incremental id
How to select a classes with same name without using incremental id

Time:01-27

enter image description hereIs there other ways to select classes with same name but in different table rows? I use html Than in jquery to select $('.className' id)... some code I would like to avoid using the id each time. Some suggestions? Thank you

HMTL
Data retrieved from the database
<tr  id="<?= $id;?>"> <!-- id 1 -->
   <td  > <?= $v['atyp'];?> </td>

 <tr  id="<?= $id;?>"> <!-- id 2 -->
   <td  > <?= $v['atyp'];?> </td>

JQUERY
<script>
$('.atyp' id).val() // some code....
</script>

So the table has multiple rows with same class name and I would like to avoid to use id to select a specific class

CodePudding user response:

Don't put <?= $id;?> to your classes:

<tr  id="<?= $id;?>"> <!-- id 1 -->
   <td  > <?= $v['atyp'];?> </td>

 <tr  id="<?= $id;?>"> <!-- id 2 -->
   <td  > <?= $v['atyp'];?> </td>
$('.atyp').val()

CodePudding user response:

You should not give multiple HTML elements the same ID.

You can select the first td with the :first-of-type selector

$("td:first-of-type")

In general you can use the :nth-of-type selector.

$("td:nth-of-type(42)")
  •  Tags:  
  • Related