Home > other >  last of type is not working while selecting dropdown from a table
last of type is not working while selecting dropdown from a table

Time:01-17

I have the following HTML and js code where I am trying to select the "Plan" dropdown using querySelector('select:last-of-type') but I am unable to select it. It is always selecting the "Gender" dropdown. Can anyone tell me why this is not working.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Welcome</title>
  </head>
  <body>
    <table id="table" >
        <thead>
          <th></th>
          <th>Name</th>
          <th>Age</th>
          <th>Gender</th>       
          <th>Plan</th>
        </thead>
        <tbody id="tbody">
          <tr id="newRow">
            <td><input type="checkbox" id="checkbox" /></td>
            <td><input type="text" id="Name" /></td>
            <td><input type="number" id="Age" /></td>
            <td>
              <select name="Gender" id="Gender">
                <option value="Male">Male</option>
                <option value="Female">Female</option>
              </select>
            </td>
            <td>
              <select name="Plan" id="Plan">
                <option value="1 Month">Monthly</option>
                <option value="3 Months">3 Months</option>
                <option value="6 Months">6 Months</option>
                <option value="12 Months">1 Year</option>
              </select>
            </td>
          </tr>
        </tbody>
      </table>
    <script>
        let dropDown = document.querySelector('select:last-of-type');
        console.log(dropDown)
    </script>
  </body>
</html>

CodePudding user response:

:last-of-type will select the last element of the type amongst its "siblings"

https://developer.mozilla.org/en-US/docs/Web/CSS/:last-of-type

#tbody td:last-of-type select would work, but its not super clean

another option you have is to query all of them, and then grab the last element:

const selectEls = document.querySelectorAll('select')
const lastSelect = selectEls.length && selectEls[selectEls.length - 1]

CodePudding user response:

You can not use "last of type" like that!

It's a relative command and is only meant to be used to query a particular type of tag (in this case 'select') under a DIRECT parent. 'document' is not a direct parent for 'select' so you are facing this error.

The above code will work if you query the 'td' under the tag 'tr' for example. (as there is only one parent -'tr' tag- that contains the tag 'td')

Also you forgot to close the second </td> tag.

  •  Tags:  
  • Related