JavaScript JavaScript and the DOM Making Changes to the DOM Creating New DOM Elements

Vic Mercier
Vic Mercier
3,276 Points

createElement

If I have two ul and I want to add a li tag in the first ul, what should I do?(With the createElement method)

2 Answers

Steven Parker
Steven Parker
172,140 Points

You'll need another method for that.

The createElement method brings a new element into existence, but does not attach it to your document. For that, you'll need something like appendChild.

Your video link shows that you're just a couple of steps away from where this will be explained. I'd suggest you keep going and you'll see examples of this after a few more videos.

Vic Mercier
Vic Mercier
3,276 Points

Sorry to asked you this stupid question.It was because I haven't done the next lesson yet. I apologize again and thanks for your answer!

Steven Parker
Steven Parker
172,140 Points

No problem. You just had a burst of enthusiastic eagerness. I can relate. :wink:

Abraham Juliot
Abraham Juliot
47,337 Points

You can select the first ul by giving it a unique id and then using the documents getElementById method, or you can use the documents querySelector method and use a css selector to get that specific tag:

  • "ul:first-of-type" or "ul:nth-of-type(1)"

With the createElement method, you need to create your li tag and then append or prepend it to the ul list using the appendChild or insertBefore method:

  • ulTag.insertBefore(liTag, ulTag.firstChild);
  • ulTag.appendChild(liTag);