HTMLTableElement: createCaption() method
MDN Web Docs · نسخهٔ df622a2a1c1e · CC BY-SA 2.5 و مجوز جداگانهٔ ناشر برای نمونهکد
{{APIRef("HTML DOM")}}
The **createCaption()** method of the {{domxref("HTMLTableElement")}} interface creates a {{HTMLElement("caption")}} element, inserts it as the first child of the given {{HTMLElement("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 {{domxref("Document.createElement()")}} and {{domxref("Node.insertBefore()")}}.
Syntax
createCaption()Parameters
None.
Return value
An {{domxref("HTMLTableCaptionElement")}}.
Examples
This example uses JavaScript to add a caption to a table that initially lacks one.
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
const table = document.querySelector("table");
const caption = table.createCaption();
caption.textContent = "This caption was created by JavaScript!";Result
{{EmbedLiveSample("Examples")}}
Specifications
{{Specifications}}
Browser compatibility
{{Compat}}
See also
- {{domxref("HTMLTableElement.createTBody()")}}
- {{domxref("HTMLTableElement.createTFoot()")}}
- {{domxref("HTMLTableElement.createTHead()")}}
- {{domxref("HTMLTableElement.deleteCaption()")}}