0

Why the first approach is not working ?

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>append method</title> </head> <style></style> <body> <div> <ul id="listclass"> <li class="list">xyz</li> <li class="list">xyz</li> <li class="list">xyz</li> </ul> </div> <script> // approach 1 // const i = document.getElementById("listclass").innerHTML; // i += `<li>abc</li>`; // approach 2 const i = document.getElementById("listclass"); i.innerHTML += `<li>abc</li>`; </script> </body> </html> what is the difference between the two approaches ? I am getting the following error if i run the first approach. append.html:20 Uncaught TypeError: Assignment to constant variable. at append.html:20:11

27th Jan 2024, 1:25 PM
susi
susi - avatar
2 Antworten
+ 1
in the first, you made the innerHTML constant. that's why you can't assign to it. In the second, the DOM element ul is constant. That's ok, since what we want to change is the innerHTML, which is still a mutable property.
27th Jan 2024, 2:57 PM
Bob_Li
Bob_Li - avatar
0
In simple terms the const keyword means that a value assigned to it can't be updated. In your first approach you added the value of I to a string which caused the error. You can try this instead of changing it's value const i = document.getElementById('listclass').innerHtml += `<li> abc</li>` In this modified version. The value of the const i variable. It is taken to be not updated
27th Jan 2024, 3:07 PM
MATOVU CALEB
MATOVU CALEB - avatar