简体   繁体   中英

Add new column to HTML table which has not table id

How can i get to add a new column in the below code, I need this to happen if there is no table id or tr id or td id.

Please check and tell me

<p>Click the button to insert new cell(s) at the beginning of the table row.</p>

<table>
  <tr>
    <td>First cell</td>
    <td>Second cell</td>
    <td>Third cell</td>
  </tr>
</table><br>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var row = ??????????????
    var x = row.insertCell(0);
    x.innerHTML = "New cell";
}
</script>

You can use getElementsByTagName for access your tables.

var row = document.getElementsByTagName("table")[0].rows[0];

https://jsfiddle.net/4rmt4xmj/1/

The answer provided by @aub using var row = document.getElementsByTagName("table")[0].rows[0]; is good but I'd like to mention an alternative approach using XPath .

You can inspect-element and then select that table and right-click -> Copy -> Copy XPath

Then you can use the following code to obtain the desired element:

var elementTable = document.evaluate( '/html/body/table' ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;
if (elementTable != null) {
  //do something
}

Here's the JsFiddle Demo

Try This

  function myFunction(){ var row = document.getElementsByTagName("table")[0].rows[0]; var x = row.insertCell(); x.innerHTML = "Last"; } 
  <table border="1"> <tr> <td>First</td> <td>Second</td> <td>Third</td> </tr> </table> <br /><br /> <button onclick="myFunction()">Try it</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM