HTML DOM टेबल createTHead() मेथड एक खाली <thead> एलिमेंट जनरेट करता है और इसे HTML दस्तावेज़ में टेबल में जोड़ता है। यदि टेबल में पहले से <thead> है, तो यह मौजूदा को लौटाता है (नया नहीं बनाता)।
सिंटैक्स
object.createTHead()
उदाहरण: टेबल हेडर बनाना
<!DOCTYPE html>
<html>
<style>
body { color: #000; background: lightblue; height: 100vh; text-align: center; }
table { margin: 2rem auto; }
caption { color: #db133a; }
.btn { background: #db133a; border: none; height: 2rem; border-radius: 2px; width: 40%; display: block; color: #fff; outline: none; cursor: pointer; margin: 1rem auto; }
.show { font-size: 1.2rem; }
</style>
<body>
<h1>DOM टेबल createTHead() मेथड डेमो</h1>
<table border="2">
<tr> <td>नाम</td> <td>रोल नं.</td> </tr>
<tr> <td>जॉन</td> <td>071717</td> </tr>
<tr> <td>जेन</td> <td>031717</td> </tr>
</table>
<button onclick="create()" class="btn">हेडर बनाएं</button>
<script>
function create() {
var tableHeader = document.querySelector('table').createTHead();
tableHeader.innerHTML = "टेबल हेडिंग";
}
</script>
</body>
</html>
आउटपुट
- प्रारंभ में: टेबल बिना thead के (पंक्तियां सीधे table में)
- "हेडर बनाएं" क्लिक:
<thead>बनाया जाता है, पहली पंक्ति इसमें चली जाती है - परिणाम: "टेबल हेडिंग" टेक्स्ट वाला हेडर सेक्शन
महत्वपूर्ण व्यवहार
- मौजूदा thead लौटाता है: यदि पहले से मौजूद है तो नया नहीं बनाता
- पंक्तियों को मूव करता है: मौजूदा पहली पंक्तियों को नए thead में ले जा सकता है
- स्ट्रक्चर सुधारता है: सेमांटिक HTML के लिए thead आवश्यक है
संबंधित मेथड्स
deleteTHead()- thead हटाता हैtHeadप्रॉपर्टी - thead एलिमेंट एक्सेस करता हैcreateTFoot()/deleteTFoot()- फुटर के लिए समान
उचित हेडर स्ट्रक्चर बनाना
function createProperHeader(table, headers) {
var thead = table.createTHead();
var row = thead.insertRow();
headers.forEach(function(headerText) {
var th = document.createElement('th');
th.textContent = headerText;
row.appendChild(th);
});
return thead;
}
// उपयोग
createProperHeader(document.querySelector('table'), ['नाम', 'ईमेल', 'फोन']);