We can create a <caption> element by using the document.createElement()
method:
var x = document.createElement("CAPTION");
Click the button to create a CAPTION element.
<!DOCTYPE html> <html> <head> <style> table, th, td { border: 1px solid black; margin-top: 20px; } </style>/*w ww. j a v a2s .co m*/ </head> <body> <button onclick="myFunction()">Test</button> <table id="myTable"> <tr> <th>Item</th> <th>Savings</th> </tr> <tr> <td>CSS</td> <td>$100</td> </tr> <tr> <td>HTML</td> <td>$50</td> </tr> </table> <script> function myFunction() { var x = document.createElement("CAPTION"); var t = document.createTextNode("Monthly savings"); x.appendChild(t); var table = document.getElementById("myTable") table.insertBefore(x, table.childNodes[0]); } </script> </body> </html>