There are a few issues here.
- Do not use duplicate IDs.
It is not valid, and will give unexpected results. Either use a class, or make the IDs unique.
- Do not do redundant DOM selection in a loop.
DOM selection is an expensive operation. It should be done once, outside the loop, then cached.
- There's no need to check for the
tagSelected
class inside the loop.
You used getElementsByClassName('tagSelected')
, so obviously they have that class.
It seems that you simply want to remove the elements with the given class.
// Fetch all elements in the document with the class 'tagSelected'
var selectTag = document.getElementsByClassName('tagSelected');
// Remove all of them.
while( selectTag[0] ) {
selectTag[0].parentNode.removeChild( selectTag[0] );
}
The reason that while( selectTag[0] ) {
works is that getElementsByClassName
returns a "live" NodeList. This means that when an element is removed from the DOM, the list is updated.
So because we're removing all the elements, all we need to do is run the loop as long as there's something at index [0]
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…