The DOM - Code Exercises

Written by Luka Učur

It's really hard to test your programming knowledge after you have completed a tutorial or some lecture. We have prepared some exercises to help out the beginner devs to solidify their understanding of the DOM. Every exercise has a brief description of the problem, starting code, links to relevant MDN docs, and expected results. Try to solve the problems without taking a peek at the solution.

If you need some additional help, you can check out our The DOM video from #lockdown learning series or contact the author of the article directly.




The DOM or the Document Object Model of the page is created after the web page is loaded. It's constructed as a tree of objects, and with it JavaScript can access and change all the elements of an HTML document.



Exercises



Fruit List

You are given some names of different fruits and an unordered list html element; add a list item for each to the unordered list.

Helpful MDN Docs links

<ul></ul>
const fruitList = ['apple', 'banana', 'tomato' ];
  • apple
  • banana
  • tomato

Solution

(click to show)
const fruitList = ['apple', 'banana', 'tomato' ];

const ulElement = document.querySelector('ul');

fruitList.forEach((fruit) => {
  const itemElement = document.createElement('li');
  itemElement.textContent = fruit;
  ulElement.appendChild(itemElement);
});

Add the CroCoder logo (image element) as a child element to the existing div element.

Helpful MDN Docs links

<div></div>
const imageSrc = 'https://crocoder.dev/icon.png';

Solution

(click to show)
  const imageSrc = 'https://crocoder.dev/icon.png';

  const divElement = document.querySelector('div');

  const imgElement = document.createElement('img');

  imgElement.src = imageSrc;

  divElement.appendChild(imgElement);

Change first and last item from an unordered list

Change the text in first and the last list item element in every unordered list element on this page. Change it to 'first' and 'last'.

Helpful MDN Docs links

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>
<ul>
  <li>a</li>
  <li>b</li>
  <li>c</li>
</ul>
<ul>
  <li>👻</li>
  <li>👽</li>
  <li>🦁</li>
</ul>
  • first
  • 2
  • last
  • first
  • b
  • last
  • first
  • 👽
  • last

Solution

(click to show)
  const firstLis = [...document.querySelectorAll('ul > li:first-child')];
  const lastLis = [...document.querySelectorAll('ul > li:last-child')];

  firstLis.forEach(li => li.textContent = 'first');

  lastLis.forEach(li => li.textContent = 'last');
Luka Učur
Learning JavaScript all the time, writing posts sometimes.