HTML DOM टेबल deleteRow() मेथड HTML दस्तावेज़ में टेबल से एक <tr> एलिमेंट हटाता है।
सिंटैक्स
object.deleteRow(index)
यहां index एक संख्या है जो हटाने के लिए पंक्ति की स्थिति निर्दिष्ट करती है। इंडेक्स 0-आधारित है और सभी पंक्तियों (हेडर सहित) पर लागू होता है।
उदाहरण: पंक्ति हटाना
<!DOCTYPE html>
<html>
<style>
body { color: #000; background: lightblue; height: 100vh; text-align: center; }
table { margin: 2rem auto; }
.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 टेबल deleteRow() मेथड डेमो</h1>
<table border="2">
<thead>
<tr> <th>नाम</th> <th>रोल नं.</th> </tr>
</thead>
<tbody>
<tr> <td>जॉन</td> <td>071717</td> </tr>
<tr> <td>जेन</td> <td>031717</td> </tr>
</tbody>
</table>
<button onclick="remove()" class="btn">पंक्ति हटाएं</button>
<script>
function remove() {
var tableFooter = document.querySelector('table').deleteRow(1);
}
</script>
</body>
</html>
आउटपुट
- प्रारंभ में: हेडर + 2 डेटा पंक्तियां
- "पंक्ति हटाएं" क्लिक: इंडेक्स 1 (पहली डेटा पंक्ति "जॉन") हट जाती है
- परिणाम: हेडर + केवल "जेन" पंक्ति शेष
महत्वपूर्ण बिंदु
- इंडेक्स 0-आधारित: 0 = पहली पंक्ति (आमतौर पर हेडर)
- सभी पंक्तियों पर लागू:
thead,tbody,tfootकी पंक्तियां शामिल - अमान्य इंडेक्स: यदि इंडेक्स सीमा से बाहर है तो त्रुटि फेंकता है
- वापसी मान: हटाई गई पंक्ति का संदर्भ (आमतौर पर उपयोग नहीं किया जाता)
सुरक्षित हटाने का पैटर्न
function safeDeleteRow(table, index) {
if (index >= 0 && index < table.rows.length) {
table.deleteRow(index);
return true;
}
return false;
}
// अंतिम पंक्ति हटाने के लिए
table.deleteRow(table.rows.length - 1);
संबंधित मेथड्स
insertRow(index)- नई पंक्ति जोड़ता हैdeleteTHead()- पूरा हेडर हटाता हैdeleteTFoot()- पूरा फुटर हटाता है