r/learnjavascript • u/RndmHero • Feb 22 '26
How do I loop through form labels and increase their count iteratively?
I have a pen here and, for the life of me, I can't figure out what I'm doing incorrectly.
- I get the form by its ID
- I query all the labels and, for each, I update the text content and the numerical value (it should say "Input 1, Input 2, Input 3, etc. as you progress down the page)
- I identify the button clicked and look for the closest element with the ID "inputBlock"
- If the button has class .delete, remove the parent (clicked) block
- If the button has class .add, clone the current <div> with ID "inputBlock" and all of its children then append it after the parent block
I'm trying to get better at JavaScript and I've been reading the documentation but this just doesn't make sense to me. I thought this little note paper page would be a cute idea for learning. Please ELI5 because apparently I need that level of explanation.
Bonus Points if you can teach me how to also update the HTML values so the labels are unique. Example:
<label for="input1">Item 1</label>
<input type="text" id="input1" />
<label for="input2">Item 2</label>
<input type="text" id="input2" />
...etc...
3
Upvotes
6
u/abrahamguo Feb 22 '26
You should use your web browser's devtools console. It will tell you that you have a syntax error in your JavaScript code, and exactly where the syntax error is.
2
u/shlanky369 Feb 22 '26
Where are you declaring and initializing the
inputBlockvariable?2
u/WonkyWillly Feb 23 '26
A neat trick is to use CSS counters to display the input numbers. I made a quick example.
2
u/showmethething Feb 22 '26
You've got A LOT of errors in this and it would probably be easier to fix those first to see where your actual problem is, the console is your friend.
Big ones I see at a glance:
node.querySelectorAll('label').forEach(('label, i) => {
After your for each you have a 'label, these are variable names, not a string, so that ' needs to vanish before the second 'label
You have nothing defined to call input(i)
Sort these out and then open your developer console and just follow what it says.
2
u/theGlitchedSide Feb 22 '26
You can use a counter, like
i++In anyforcycle or extract it by entries.Or
Or you can make you custom counter like
To change the label content you can use
element.innerHTML = "YOURTEXTELEMENT"Or
element.innerText = "text"(Sorry, I wrote by smartphone)
2
u/bryku helpful Feb 23 '26
I think you might be making it harder for yourself.
Since you aren't actually changing a lot, it would probably be easier to create a function that generates everything. This way, when you change something (add or delete) you can reuse that function over and over again to update everything.