Id of option tag’s are same, so whenever I set my option tag value bydefault it will set first tag value and stop there, so how to solve this?

<!DOCTYPE html>
 <html lang="en">
   <body>
    <table id="tableTag">
     <tr>
      <td>System</td>
      <td>
       <select name="">
        <option value="1" id="1">1</option>
        <option value="2" id="2">2</option>
        <option value="3" id="3">3</option>
       </select>
     </td>
    </tr>
    <tr>
     <td>Strategy</td>
     <td>
      <select name="">
        <option value="1" id="1">1</option>
        <option value="2" id="2">2</option>
        <option value="3" id="3">3</option>
      </select>
     </td>
    </tr>
   </table>

  <script>
   let defaultValue = 2;
   let arr = [];
   let getValue = document.querySelectorAll('option');
   for(let i = 0; i<getValue.length; i++){
     arr.push(getValue[i].id);
   }
   for (let j = 0; j < arr.length; j++) {
     const element = arr[j];
     if(defaultValue == element){
     let optionId = document.getElementById(element);
     optionId.selected = true;
   }
  }
 </script>

</body>
</html>

I am begginer in javascript Kindly help me to find better solution. Id of option tags are same, so whenever I set my option-tag value by default it will set first tag value and stop there, so how to solve this?

Answer

To select the option and set the selected attribute you do not need to assign id attributes, You can simply loop through the nodelist and assign the attribute if the node matches. Alternatively you can use a more complex expression in querySelector to target the specific option.

As others have noted – IDs must be unique to be valid.

let defaultValue = 2;
let arr = [];

document.querySelectorAll('option').forEach(opt=>{
  arr.push(opt.value); // this is not really required
  if( opt.value==defaultValue )opt.selected=true;
});


// OR...
document.querySelector('select[name="strategy"] option[value="2"]').selected=true
<table id='tableTag'>
 <tr>
  <td>System</td>
  <td>
   <select name='system'>
    <option value='1'>1
    <option value='2'>2
    <option value='3'>3
   </select>
 </td>
</tr>
<tr>
 <td>Strategy</td>
 <td>
  <select name='strategy'>
    <option value='1'>1
    <option value='2'>2
    <option value='3'>3
  </select>
 </td>
</tr>
</table>