If i fetched all elements of HTML doc and store them in an array.
Now suppose i delete some element using jquery remove() method. I know it would delete its sub-child too. Now i want to traverse the list and want to know which child elements are deleted too.
Look at this code :-
$(document).ready(function() {
var list = $('*');
for (var i=0; i<list.length; i++) {
console.log(i + " " + list[i].tagName);
}
$("table").remove();
for (var i=0; i<list.length; i++) {
if ($(list[i]).parent().length == 0) console.log(list[i].tagName + "does not exist in dom now");
else console.log(i + " " + list[i].tagName + " " + $(list[i]).parent().get(0).tagName);
}
});
HTML part is :-
<div>
<table>
<tr>
<td> Hi this is Sachin </td>
<td> Hi this is Rahul </td>
</tr>
</table>
</div>
And the output I am receiving is :_
0 HTML parent.html:9
1 HEAD parent.html:9
2 SCRIPT parent.html:9
3 SCRIPT parent.html:9
4 BODY parent.html:9
5 DIV parent.html:9
6 TABLE parent.html:9
7 TBODY parent.html:9
8 TR parent.html:9
9 TD parent.html:9
10 TD parent.html:9
0 HTML undefined parent.html:14
1 HEAD HTML parent.html:14
2 SCRIPT HEAD parent.html:14
3 SCRIPT HEAD parent.html:14
4 BODY HTML parent.html:14
5 DIV BODY parent.html:14
TABLEdoes not exist in dom now parent.html:13
7 TBODY TABLE parent.html:14
8 TR TBODY parent.html:14
9 TD TR parent.html:14
10 TD TR
I don’t understand why td and tr are showing their parents. They would be considered as deleted too. Is there any other way to find out which are the deleted items in my list now.
Thanks in advance
The problem is your check to see if an element has a parent or not:
Just because you have removed an element from the DOM doesn’t mean its descendants have been removed from that element. They have been removed from the DOM (since their parent has), but they all still have that parent.
You could use
closestto check if the element has abodyancestor instead:Since the elements are no longer in the DOM, they shouldn’t have a
bodyancestor.As a side note, since
0evaluates tofalse, you can simplify your condition a little: