-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>

2
  • 2
    You are making your list shorter by one in every iteration. Btw, please declare your variables. Commented Oct 10, 2022 at 20:05
  • 1
    <alert> is not a valid Custom HTML element: Custom elements must have a dash in their names: stackoverflow.com/questions/22545621/… Commented Oct 10, 2022 at 20:18

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.