I have the following HTML:
<html>
<head><title>Title</title></head>
<body>
<div id='div2'>
<a href='#'>1</a>
<div id='div1'>
<a href='#'>2</a>
</div>
</div>
</body>
</html>
… and the following Javascript code, which I’m running through Greasemonkey:
var nodes = document.body.getElementsByTagName('a');
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
node.parentNode.removeChild(node);
}
I would expect it to find and remove all A tags; instead it finds the first, but not the second. As far as I can tell it’s having difficulty with the way the second A tag is nested.
Could someone please let me know how to remove all the tags, using getElementsByTagName? There are reasons I’d prefer not to use XPath if at all possible.
Capture the length and remove in reverse order. This will eliminate side effects.
But a better way…
Add this directive to your header:
Then your whole code becomes: