+ 1
What's wrong with this code?
HTML: <!DOCTYPE html> <html> <head> <script> function addPara() { var para = document.createElement("p"); p.innerHTML = "Hello World!"; //Or var nodeText = createTextNode("Hello World!") } </script> </head> <body> <button onclick="addPara()">New paragraph</button> </body> </html> This code only outputs the button with no functionality. I'm new to coding, and what I'm attempting to code is when the button is clicked, a new paragraph with the text of "Hello World!" will be created beneath it. Once that works, I'm looking foward to make the paragraph editable to custom text so I'm guessing "Hello World!" should be placeholder text. Sorta like a viewable comment section when you come to think about it.
5 Answers
+ 2
In order to make the paragraph appear, you have to use the appendChild method.
document.body.appendChild(para);
Also, in the 3rd line of the script tag, you should replace 'p' with 'para'.
Very interesting projectđ! Good luck!
+ 4
Following below codes to add extra element to body:
<!DOCTYPE html>
<html>
<head>
<script>
function addPara() {
var para = document.createElement("p");
var nodeText = document.createTextNode("Hello World!");
para.appendChild(nodeText);
document.body.appendChild(para);
}
</script>
</head>
<body>
<button onclick="addPara()">New paragraph</button>
</body>
</html>
https://code.sololearn.com/WbFIfQ0ZnJ4C/?ref=app
+ 1
Oh, ok thank you!
0
You 're welcome!
0
Same output, good! đI'm going to make another button that'll clear the new paragraphs.