Exercises regarding the Document Object Model (DOM)
HTML
<div id="task1wrapper"> <h2 id=task1-header>Hello from task 1</h2> <img src="https://placekitten.com/g/600/500" /> <button onclick="task1()">Click me to run this</button> </div>
Javascript
function task1() { var image = document.getElementsByTagName('img')[1]; image.src = 'https://placekitten.com/g/200/200'; var header = document.getElementById('task1-header'); header.style.color = 'blue'; }
Results
Click on button to see the header change colour and the image change in both picture and size.
Hello from task 1
HTML
<div id="task2wrapper"> <h2>This is task 2</h2> <button onclick="task2()">Click to add content</button> </div>
Javascript
function task2() { var theP = document.createElement('p'); var theText = document.createTextNode('There is no danger here'); theP.appendChild(theText); var task2wrapper = document.getElementById('task2wrapper'); task2wrapper.appendChild(theP); }
Results
Click on the button to add content. Content will be added below the button. The same content will be added repeatedly if you keep clicking the button.
This is task 2
HTML
<div id ="task3wrapper"> <h2>This is task 3</h2> <div id="task3-square" style="height: 50px; width: 50px; background: red;"></div> </div>
Javascript
function task3(){ var theSquare = document.getElementById('task3-square'); theSquare.addEventListener('mouseover',function(){ alert('Hey, look at my red square!'); }); } task3(); // to run task3
Results
Run the mouse over the red square to get a silly alert.
This is task 3
HTML
<div id="task4wrapper"> <h2>This is task 4</h2> <a id="task4-link" href="https://LeedsWebDev.org">Leeds Web Dev</a> </div>
Javascript
function task4() { var theLink = document.getElementById('task4-link'); var myInterceptionFunction = function(event) { event.preventDefault(); alert('Why leave my site?'); } theLink.addEventListener('click',myInterceptionFunction); } task4();
HTML
<div id="task5wrapper"> <h2>This is task 5</h2> <form action="/la-di-da"> <fieldset> <div> <label for="task5-input">Enter a number</label> <input id="task5-input" name="my-number" placeholder="Fill in a number"/> <button id="task5-submit" type="submit">Submit</button> </div> <p id="task5-output">The number multiplied by 5 will go here</p> </fieldset> </form> </div>
Javascript
function task5(){ var theInput = document.getElementById('task5-input'); var theButton = document.getElementById('task5-submit'); var theOutput = document.getElementById('task5-output'); var mySubmitFunction = function(dave){ dave.preventDefault(); theOutput.innerHTML = theInput.value + ' * 5 = ' + (5 * theInput.value); } theButton.addEventListener('click',mySubmitFunction); } task5();