Search code examples
javascripttypescriptangular7angular8

How to access table's last column in pure javascript or typescript


Tried to access last column for each row in pure javascript not in jquery but not working.Anyone know please help to find the solution.

app.component.html:

<div id="contentId">
<table>
  <thead>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </thead>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td><select><option>Select</option><option value="test1">Test 1</option><option value="test2">Test 2</option></select></td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td><select><option>Select</option><option value="test1">Test 1</option><option value="test2">Test 2</option></select></td>
  </tr>
  <tr>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td><select><option>Select</option><option value="test1">Test 1</option><option value="test2">Test 2</option></select></td>
  </tr> 
</table>
</div>

Demo: https://stackblitz.com/edit/amexio-breadcrumb-demo-jyxytf?file=src/app/app.component.ts


Solution

  • I am not sure why you want it in pure javascript way while you use angular,

    Anyhow I am able to make a solution for you in pure javascript way with dom querySelector() methods ..

    ngOnInit(){
    
      const gettable = document.getElementById("contentId").querySelector('table');
      const rows = gettable.getElementsByTagName('tr');
    
      for (let i=0; i<rows.length; i++)
      {
        const columns = rows[i].getElementsByTagName("td");
        const lastColumn = columns[columns.length - 1];
        const select = lastColumn.querySelector('select');
        select.addEventListener('change', this.getEvent.bind(this, select))
      }
    
    }
    
    getEvent(selectedItem){  
      console.log(selectedItem.value);
      return event;
    }
    

    I have made a solution to retrieve each select box value at last of each row on selection..

    Forked Stackblitz here ...

    Update:

    If you are using primeng table and if you need to retrieve the value from the table (p-table), You can use angular elementRef and get the value using,

    const table = this.elementRef.nativeElement.querySelectorAll('p-table table');
    

    And the table will gets initialized completely inside ngAfterviewInit lifecycle hook hence changed from ngOnInit() hook.

    Also added ChangeDetectionStrategy to detect changes on select box value(s)..

    Updated stackblitz with primeng: https://stackblitz.com/edit/primeng-tables-ubgkcm