how to dynamically append the value of a=5 to the already created div tag?

Viewed 23

i know append child can only be used to a node . here b is not a node . thats why 5 is not appending . but if i want to append that then how will i ?

//html

<div></div> //already created

//script

<script>
let a=5;
let b=document.getElementsByTagName("div") //div is targeted
b.appendChild(a)         //b.appendchild() is not a function
</script> //

i know append child can only be used to a node . here b is not a node . thats why 5 is not appending . but if i want to append that then how will i ?

2 Answers

The word elements in .getElementsByTagName is pural. what's happening is that you are getting a list of elements with tag name "div". Either you can add [0] to the end or change the div to and do document.getElementById("appendSmt") (singular).

Append Child doesn't work like that. You need to use .innerText (String) to display a value like that.

It's quite simple. Add id attribute in the div element.

<div id="idNameHere"></div>

And then use that id name in the javascript.

let a = 5;
document.getElementById("idNameHere").innerHTML = a; // You can also use innetText
Related