/

HTML / CSS / JavaScript Tutorial

JavaScript tr object method: insertCell()

[this page | pdf | back links]

The insertCell() method of the JavaScript DOM object corresponding to the HTML <tr> element inserts a cell into a table row.

 

It has the following syntax with the following parameters:

 

object.insertCell(index)

 

Parameter

Required / Optional

Description

index

Required (see below)

Index position where cell is to be inserted (index starts at 0). Using zero sometimes inserts a new cell at the start and sometimes at the end depending on browser. Using -1 inserts after the end of the existing last row.

 

Note: the index parameter is required by some browsers but optional for others.

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,td,tr,caption {border: thin solid black; border-collapse: collapse;}
</style>
</head>
<body>
Table row objects support insertCell() and deleteCell() methods, but
the precise cells inserted or deleted can vary according to browser<br><br>
<span id="element"></span>

<script>
var x = document.createElement("TABLE");
x.createCaption().innerHTML="A table";

var y0 = x.insertRow(0);
var y00 = y0.insertCell(0);
y00.innerHTML = "col1";
var y01 = y0.insertCell(1);
y01.innerHTML = "col2";
var y02 = y0.insertCell(1);
y02.innerHTML = "col3";
var y02 = y0.deleteCell(1);
document.getElementById("element").appendChild(x);
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodTrInsertCell() {
  var z = document.createElement("TR"); return !!z.cell;
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript DOM (and BOM)


Desktop view | Switch to Mobile