Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript DOM Scripting By Example Adding and Removing Names Registering Names

Primadonna Javier
seal-mask
.a{fill-rule:evenodd;}techdegree
Primadonna Javier
iOS Development Techdegree Student 4,236 Points

ul.createElement is not a function error?

Hi Everyone,

Why am I getting this error on the code above?

Uncaught TypeError: ul.createElement is not a function at HTMLFormElement.<anonymous>

Thanks!

var form = document.getElementById('registrar');
var input = form.querySelector('input');

form.addEventListener('submit', function(e){
    e.preventDefault();
    const text = input.value;
    input.value = '';
    const ul = document.getElementById('invitedList');
    const li = ul.createElement('li');
    li.textContent = text;
    ul.appendChild(li);//add item to the list
});

2 Answers

Tim Acker
seal-mask
PLUS
.a{fill-rule:evenodd;}techdegree seal-36
Tim Acker
Front End Web Development Techdegree Graduate 31,247 Points

You create an element on the document object first and then append it as a child to the parent node.

const li = document.createElement('li');
li.textContent = text;
ul.appendChild(li);
andren
andren
28,558 Points

You get the error pretty much for the exact reason the error states you do, createElement is not a function that exists on HTML elements like ul. The createElement function belongs to the document object. Just like the getElementById function does.

So if you change ul to document like this:

var form = document.getElementById('registrar');
var input = form.querySelector('input');

form.addEventListener('submit', function(e){
    e.preventDefault();
    const text = input.value;
    input.value = '';
    const ul = document.getElementById('invitedList');
    const li = document.createElement('li');
    li.textContent = text;
    ul.appendChild(li);//add item to the list
});

Then your code should work fine.