Using appendChild multiple times with the same node in JS
Asked Answered
C

2

21

I'm writing a form validation script for a form with multiple ratings, and I'd like to insert a bit of text that says "give a rating!" for each rating the user misses. I wrote the code below to do this, but I'm running into a problem where the give_rating node is only appended to the last node on the form. I know that this is because appendChild basically moves a node instead of duplicating it, and I tried solving this using cloneNode but that just breaks my JS entirely.

Anyway, here's the code. What am I doing wrong?

Thanks for your help,

Chris

var give_rating = document.createElement('span');
give_rating.className='small red';
give_rating.innerHTML = '<strong> &nbsp;Give a rating!</strong>';

document.getElementById('rating1').appendChild(give_rating);
document.getElementById('rating2').appendChild(give_rating);

When I use the code above code give_rating is only appended to 'rating2'.

document.getElementById('rating1').appendChild(give_rating.cloneNode(True));
document.getElementById('rating2').appendChild(give_rating.cloneNode(True));

When I use this code the entire script fails. How do I add an instance of "Give a rating!" for each rating on my form that the user fails to fill out?

Contravallation answered 19/11, 2010 at 4:52 Comment(0)
F
16

JavaScript is case-sensitive: True should be true (lower case).

Filefish answered 19/11, 2010 at 4:54 Comment(1)
OMG casablanca, I literally downloaded Firebug right after submitting this question, ran Console and figured this out. Thanks for your response. JS drives me nuts :)Contravallation
R
10
  1. You can only insert the created html elements or document pieces once. So, you have to call the cloneNode() function.
  2. The javascript is case-sensitive. So, it should be cloneNode(true), instead of cloneNode(True).
  3. You can turn on the javascript debugger of the browser (both Chrome and IE/Edge) by pressing F12. Then you can see what happen to your script.
Recreant answered 3/11, 2017 at 2:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.