HTML DOM टेबल insertRow() मेथड एक खाली <tr> एलिमेंट जनरेट करता है और इसे HTML दस्तावेज़ में टेबल में जोड़ता है।
सिंटैक्स
object.insertRow(index)
यहां index एक संख्या है जो सम्मिलित करने के लिए पंक्ति की स्थिति निर्दिष्ट करती है। इंडेक्स 0-आधारित है।
उदाहरण: नई पंक्ति बनाना
<!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 टेबल insertRow() मेथड डेमो</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 table = document.querySelector('table');
var tableRow = table.insertRow(1);
tableRow.innerHTML = "<td>मैक्सिमिलियन</td><td>081717</td>";
}
</script>
</body>
</html>
आउटपुट
- प्रारंभ में: 3 पंक्तियां (1 हेडर जैसी + 2 डेटा)
- "पंक्ति बनाएं" क्लिक: इंडेक्स 1 पर नई पंक्ति डाली जाती है (पहली डेटा पंक्ति से पहले)
- परिणाम: नई पंक्ति "मैक्सिमिलियन, 081717" दूसरी पंक्ति बन जाती है
इंडेक्स व्यवहार
| इंडेक्स | परिणाम |
|---|---|
0 |
पहली पंक्ति के रूप में सम्मिलित (वर्तमान पहली पंक्ति को नीचे धकेलता है) |
1 |
दूसरी पंक्ति के रूप में सम्मिलित |
-1 |
अंत में सम्मिलित (अनुशंसित) |
rows.length |
अंत में सम्मिलित (समान -1) |
| बाहर की सीमा | त्रुटि फेंकता है |
सर्वोत्तम अभ्यास
- सुरक्षित सम्मिलन:
table.insertRow(-1)याtable.insertRow(table.rows.length)अंत में जोड़ने के लिए - सेल जोड़ना:
row.insertCell()का उपयोग करेंinnerHTMLके बजाय - tbody में सम्मिलन: विशिष्ट
tbody.insertRow()का उपयोग करें सेक्शन नियंत्रण के लिए
सेल्स के साथ पूर्ण उदाहरण
function addRow(table, data) {
var row = table.insertRow(-1); // अंत में जोड़ें
data.forEach(function(cellData) {
var cell = row.insertCell();
cell.textContent = cellData;
});
return row;
}
// उपयोग
addRow(document.querySelector('table'), ['नया', 'डेटा', 'पंक्ति']);