Javascript Reference - HTML DOM Table createCaption() Method








The createCaption() method creates an empty <caption> element and adds it to the table.

Browser Support

createCaption Yes Yes Yes Yes Yes

Syntax

tableObject.createCaption() 

Parameters

None

Return Value

The newly created (or an existing) <caption> element.





Example

The following code shows how to create and delete a <caption> element.


<!DOCTYPE html>
<html>
<head>
<style>
table, td {<!--from   w  w  w. j  a va  2s. com-->
    border: 1px solid black;
}
</style>
</head>
<body>
<table id="myTable">
  <tr>
    <td>cell 1</td>
    <td>cell 2</td>
  </tr>
  <tr>
    <td>cell 3</td>
    <td>cell 4</td>
  </tr>
</table>
<br> 

<button onclick="myCreateFunction()">Create caption</button>
<button onclick="myDeleteFunction()">Delete caption</button>

<script>
function myCreateFunction() {
    var table = document.getElementById("myTable").createCaption();
    table.innerHTML = "<b>My table caption</b>";
}

function myDeleteFunction() {
    document.getElementById("myTable").deleteCaption();
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to create a <caption> element with some text for a table.


<!DOCTYPE html>
<html>
<head>
<style>
table, td {<!--   ww  w .  j a  v a  2 s.  c o m-->
    border: 1px solid black;
}
</style>
</head>
<body>
<table id="myTable">
  <tr>
    <td>cell 1</td>
    <td>cell 2</td>
  </tr>
  <tr>
    <td>cell 3</td>
    <td>cell 4</td>
  </tr>
</table>
<br> 

<button onclick="myFunction()">test</button>

<script>
function myFunction() {
    var table = document.getElementById("myTable").createCaption();
    table.innerHTML = "<b>My table caption</b>";
}
</script>

</body>
</html>

The code above is rendered as follows: