Reputation: 11
I am new to JavaScript so I am trying to learn the concepts first, that's why I am gonna attach two code samples, and I want to know why the second sample doesn't work.
The issue is: when I am trying to append the li element using sample 2 it doesn't work, but why?
sample 1
<body>
<h1>This is my List </h1>
<button onclick="j()">click me</button>
<script>
function j()
{
var ul = document.createElement('ul');
ul.innerHTML = 'List:'
document.body.appendChild(ul);
let u = document.createElement('li');
u.innerHTML = 'person';
ul.appendChild(u);
}
</script>
</body>
sample 2
<body>
<h1>This is my List </h1>
<button onclick="j()">click me</button>
<script>
function j()
{
var ul = document.createElement('ul');
ul.innerHTML = 'List:'
document.body.appendChild(ul);
let u = document.createElement('li');
u.innerHTML = 'person';
document.getElementsByTagName("ul").appendChild(u); //ul here is the one created within the function.
}
</script>
</body>
Upvotes: 1
Views: 759
Reputation: 43156
document.getElementsByTagName()
returns a collection.
So your code should be document.getElementsByTagName("ul")[0].appendChild(u)
assuming you only have this one <ul>
in your document.
You can use document.querySelector("ul")
instead to find a specific element.
Side note: ul.innerHTML = 'List:'
is invalid HTML, <ul>
's HTML should only contain <li>
elements.
You can do ul.innerHTML = '<li>List:</li>'
or you should consider using another element like <h1>
to hold the title.
Upvotes: 3