-1

I have a project that I am doing for a class involving making custom HTML tags using JavaScript. I have a for loop to loop over every time the tag is used. When I run the code, it only loops over every odd tag. I am trying to make an alert tag in html.

for (i = 0; i < document.querySelectorAll("alert").length; i++) {
  console.log(document.querySelectorAll("alert")[i].innerHTML);
  document.querySelectorAll("alert")[i].remove();
}
<body>
  <alert>Hello!</alert>
  <alert>How do you do?</alert>
  <alert>Are you doing good?</alert>
  <alert>I hope you are!</alert>
  <alert>Bizzle</alert>
  <alert>Fizzle</alert>
  <alert>Grizzle</alert>
</body>
isherwood
  • 58,414
  • 16
  • 114
  • 157
SipSup
  • 14
  • 4
  • 2
    You are making your list shorter by one in every iteration. Btw, please declare your variables. – Konrad Oct 10 '22 at 20:05
  • 1
    `` is not a valid Custom HTML element: Custom elements must have a dash in their names: https://stackoverflow.com/questions/22545621/do-custom-elements-require-a-dash-in-their-name – Dai Oct 10 '22 at 20:18

1 Answers1

6

Problem

You are making your list shorter in every iteration

Solution

Declare your list before the loop

const items = document.querySelectorAll("alert")
for (let i = 0; i < items.length; i++) {
  alert(items[i].innerHTML);
  items[i].remove();
}
<alert>Hello!</alert>
<alert>How do you do?</alert>
<alert>Are you doing good?</alert>
<alert>I hope you are!</alert>
<alert>Bizzle</alert>
<alert>Fizzle</alert>
<alert>Grizzle</alert>
Konrad
  • 21,590
  • 4
  • 28
  • 64
  • 1
    Thanks! I just thought about it and I am removing the element causing the for loop to go to the next one instead of the one before it. Edit: I used a while loop to check if there was a value in the node list instead of the for loop. – SipSup Oct 10 '22 at 20:13