HTMLTableElement: createCaption() method
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The createCaption() method of the HTMLTableElement interface creates a <caption> element, inserts it as the first child of the given <table>, and returns it. If the table already has a <caption> element child, this method returns the first such child without creating one.
When creation is needed, this method creates and inserts the element directly, without requiring separate calls to methods such as Document.createElement() and Node.insertBefore().
Syntax
js
createCaption()
Parameters
None.
Return value
Examples
This example uses JavaScript to add a caption to a table that initially lacks one.
HTML
html
<table>
<tbody>
<tr>
<td>Cell 1.1</td>
<td>Cell 1.2</td>
<td>Cell 1.3</td>
</tr>
<tr>
<td>Cell 2.1</td>
<td>Cell 2.2</td>
<td>Cell 2.3</td>
</tr>
</tbody>
</table>
JavaScript
js
const table = document.querySelector("table");
const caption = table.createCaption();
caption.textContent = "This caption was created by JavaScript!";
Result
Specifications
| Specification |
|---|
| HTML> # dom-table-createcaption-dev> |