0
Why h1(even other tags as well) tag is not working properly with appendChild method?
I just created new h1 tag with some textContent through JavaScript & wanted to append this h1 tag in HTML div tag <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <div id="myi2"></div> <script> let a =document.getElementById("myi2") //creating new element <h1></h1> let b=document.createElement("h1") //creating a new text let c=document.createTextNode("I am learning javaScript") //appending the text to h1 tag let d=b.appendChild(c) //appending the h1 tag to div tag a.appendChild(d) </script> </body> </html>
2 ответов
+ 1
you can also use innerHTML
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<div id="myi2"></div>
<script>
let a =document.getElementById("myi2")
//creating new element <h1></h1>
let b = document.createElement("h1")
b.innerHTML = ("I am learning javaScript")
a.appendChild(b)
</script>
</body>
</html>
your way also works but you made a mistake a.appendChild(d) it should be a.appendChild(b)
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<div id="myi2"></div>
<script>
let a =document.getElementById("myi2")
//creating new element <h1></h1>
let b=document.createElement("h1")
//creating a new text
let c=document.createTextNode("I am learning javaScript")
//appending the text to h1 tag
let d=b.appendChild(c)
//appending the h1 tag to div tag
a.appendChild(b) // this line
</script>
</body>
</html>