Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to create a table caption with JavaScript DOM?
To create a table caption using JavaScript DOM, use the createCaption() method on a table element. This method adds a <caption> element to the table, which displays as a title above the table content.
Syntax
table.createCaption()
Return Value
Returns the newly created <caption> element, which can be styled or modified with text content.
Example
Here's how to create a table caption dynamically using JavaScript:
<!DOCTYPE html>
<html>
<head>
<script>
function captionFunc(x) {
document.getElementById(x).createCaption().innerHTML = "Demo Caption";
}
</script>
</head>
<body>
<table style="border:2px solid black" id="newtable">
<tr>
<td>One</td>
<td>Two</td>
</tr>
<tr>
<td>Three</td>
<td>Four</td>
</tr>
<tr>
<td>Five</td>
<td>Six</td>
</tr>
</table>
<p>
<input type="button" onclick="captionFunc('newtable')" value="Display Table Caption">
</p>
</body>
</html>
Alternative Method: Using createElement()
You can also create captions by manually creating the <caption> element:
<!DOCTYPE html>
<html>
<body>
<table id="myTable" border="1">
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
</tr>
</table>
<button onclick="addCaption()">Add Caption</button>
<script>
function addCaption() {
let table = document.getElementById("myTable");
let caption = document.createElement("caption");
caption.innerHTML = "My Table Caption";
caption.style.fontWeight = "bold";
table.insertBefore(caption, table.firstChild);
}
</script>
</body>
</html>
Key Points
- The
createCaption()method automatically positions the caption at the top of the table - If a caption already exists, this method returns the existing one instead of creating a new one
- Captions are semantically important for accessibility and table organization
- You can style captions using CSS or inline styles
Conclusion
Use createCaption() for a simple way to add table captions dynamically. This method ensures proper semantic structure and accessibility for your HTML tables.
Advertisements
