Reputation: 13
I am trying remove 2 tables from simple html page. The page contain only 2 tables, Heres the page code:
<html>
<body>
<h3>Table 1</h3>
<table class="details" border="1" cellpadding="0" cellspacing="0">
<tbody><tr>
<th>1</th>
<td>2</td>
</tr>
</tbody></table>
<h3>Table 2</h3>
<table class="details" border="1">
<tbody><tr>
<th>1</th>
<td>2</td>
</tr><tr>
<th>3</th>
<td>4</td>
</tr>
</tbody></table>
</body>
</html>
I have no problem removing one of the tables using:
var elmDeleted = document.getElementsByClassName('details').item(0);
elmDeleted.parentNode.removeChild(elmDeleted);
or
var elmDeleted = document.getElementsByClassName('details').item(1);
elmDeleted.parentNode.removeChild(elmDeleted);
But I fail to remove both tables using those command in a row on my user script:
var elmDeleted = document.getElementsByClassName('details').item(0);
elmDeleted.parentNode.removeChild(elmDeleted);
var elmDeleted = document.getElementsByClassName('details').item(1);
elmDeleted.parentNode.removeChild(elmDeleted);
Please advise
Upvotes: 0
Views: 1294
Reputation: 926
Sebastian's answer really is the answer you'll be looking for, but for clarity, I'll show how you could do it: You could either do
var elmDeleted = document.getElementsByClassName('details').item(0);
elmDeleted.parentNode.removeChild(elmDeleted);
var elmDeleted = document.getElementsByClassName('details').item(0);
elmDeleted.parentNode.removeChild(elmDeleted);
Watch the fact that I'm removing the .item[0]
both times; it'll remove the first one on the page both times.
Else, this:
var elmDeleted = document.getElementsByClassName('details').item(1);
elmDeleted.parentNode.removeChild(elmDeleted);
var elmDeleted = document.getElementsByClassName('details').item(0);
elmDeleted.parentNode.removeChild(elmDeleted);
... Which will remove the second, then the first one.
To be (what I call) neat: (==more compact)
for(i=0;i<2;i++)(temp=document.getElementsByClassName('details').item(0)).parentNode.removeChild(temp);
As a side note, since you say that there'll be only 2 tables on the page, you can replace every document.getElementsByClassName('details')
with document.getElementsByTagName('table')
.
Also, in my compact version, you can replace the i<2
with i<document.getElementsByClassName('details').length
to remove all 'detail'-tables instead of just the first two.
Hope this helped :)
Upvotes: 1
Reputation: 50928
Once you remove the old table #0, the old table #1 becomes the new table #0. Thus, if you try to get table #1, it'll fail.
Upvotes: 1