-3

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 ?

Rahul Mohanty
  • 342
  • 3
  • 9
  • Give that div `id` and then `document.getElementById('givenID').innerHTML = a` – Aleksa Ristic Sep 17 '22 at 06:08
  • `//div is targeted` **No:** `//divS ARE targeted`. The DOM API is not jQuery. Use `document.querySelector('div')` instead. Also you need to pass a `Node` object to `appendChild`, not a `string`. – connexo Sep 17 '22 at 06:43

2 Answers2

1

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.

1

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
Veeramani R
  • 145
  • 7
  • `.innerHTML = a` _overwrites_ the content of the div. OP wants to _add_ to the div, so you need to use `.innerHTML += a` if used in this way. – Michel Sep 17 '22 at 06:36
  • Yes, you're right! If `
    ` has some other elements and if we want to append as a child element, we can use that.
    – Veeramani R Sep 17 '22 at 06:55