Exercise 10.11
This is Exercise 10.11, lecture on modifying DOM with Javascript, used in the course IDATA2301 Web technologies at NTNU, campus Aalesund.
Purpose
The purpose of the exercise is to learn how you can remove elements from the DOM and add new ones.
Instructions
Part 1 - Add/remove a table row
- Create a document and add a table with two columns.
- Add three rows in it, with any content you want.
- Add a button with text "Add a row".
-
Every time the user clicks on the button, add a new row to the table
with text "Hello" in one column and "World" in the other column.
Hint:
<table>
has<tbody>
as the direct child, rows should be added to the<tbody>
element not to the<table>
directly! - Extend the previous example: add a button "Remove last row". When the user clicks on it, the last row of the table is removed.
- If the table has three or fever rows left, an alert must be shown saying "Can't remove the last 3 rows", and the row must not be removed.
Part 2 - div inside a box
-
Add a
<div>
element to the page, set its height and width to20px
, background color togreen
. -
Make the
<div>
element escape - when the user moves the mouse over it, the<div>
element is removed from the place it currently sits and is moved to a random place in the table above. I.e, it is added to a random row and random column inside the table you created in the previous steps.
Part 3 - div outside the box
Extra challenge: add some more content to the page (some headings, paragraphs, etc.) and make the div escape randomly at any place in the DOM tree. I.e., don't limit its placement to the table.
Solution
You can find a solution here.