M04 - DOM, Document Object Model
Web browser as a programming environment
Browser has a DOM (Document Object Model) and BOM (Browser Object Model) which are accessible from JavaScript programming. Window object is top most object which uses BOM to define web browser window and its properties. DOM is used to get connection to loaded HTML document.
BOM
BOM will give for example location
and navigator
objects. location
object are used to detect used URL or redirect browser to new address. navigator
object can be used to detect browser version etc. You can use functions to open/close windows, alerts, prompts, etc. These objects aren't so important in this course.
DOM
DOM is a programming interface to modify loaded HTML/CSS document from JavaScript. DOM will describe loaded document as an objects. Every element is a node in DOM. Developer can use different functions to find element from DOM, like firstChild
, lastChild
, childNodes
, parentNodes
or using different functions like document.getElementById()
or document.getElementsByTagName()
.
Note
DOM descripes whole HTML document as a DOM tree, which has a nodes.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
You can use for example http://software.hixie.ch/utilities/js/live-dom-viewer/# service to see DOM nodes.
Above HTML has (for example):
- HTML node has three child: HEAD, #text ja BODY. (#text is newline character after HEAD)
- UL node is parent for both LI nodes
- text, li, text, li and text are siblings
Finding elements from DOM
Basicly you are using a following functions:
getElementById
function returns an element with a specified value with id (only one).
Example: Find a demo node and change text and text color to blue.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
getElementsByName
function returns a collection of elements with a specified name.
Example: Find all elements by name
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
getElementsByTagName
function returns a collection of all elements with a specified tag name.
Example: Find elements by tag name
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
getElementsByClassName
function returns a collection of elements with a specified class name(s).
Example: change target text
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
querySelector
function returns the first element that matches a CSS selector.
Example: Find a first class which has value sini
and change background color to blue
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
querySelectorAll
function returns all elements that matches a CSS selector(s).
Example: Change paragraph background color to blue
if it has a class=sini
attribute.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
Adding elements or content
You can use for example a following methods to modify elements:
document.createElement
add a new elementdocument.createTextNode
add a new text nodeelement.appendChild
adding a element to some element (last)
A few examples
- Adding a new
li
element to unordered list.1 2 3 4
<ul id="demolist"> <li>First</li> <li>Second</li> </ul>
Will modify DOM:1 2 3 4 5 6 7 8 9 10
// find a node let ulnode = document.getElementById("demolist"); // create a new node let linode = document.createElement('li'); // create a new text node == text let litext = document.createTextNode('Third'); // append text node to li element linode.appendChild(litext); // append li element to ul element ulnode.appendChild(linode);
1 2 3 4 5
<ul id="demolist"> <li>First</li> <li>Second</li> <li>Third</li> </ul>
Note
There are quite a many different functions which you can use to modify DOM like insertBefore
, insertAfter
, append
, append
, append
, after
etc... you will learn more later in exercises.
Remove elements
You can use remove()
function to remove node and parentElem.removeChild()
function to remove child element.
Example - Remove clicked li
element from ul
list.
1 2 3 4 5 |
|
1 2 3 4 5 6 7 8 |
|
Example - Remove all li
elements from ul
list.
1 2 3 4 5 |
|
1 2 3 4 5 6 7 8 |
|
HTML DOM Events
DOM nodes will generate different events. Here are a common list of events:
click
mouse click inside some DOM element/nodemouseover
,mouseout
,mousedown
,mouseup
,mousemove
,contextmenu
mouse eventssubmit
,focus
form and it fields eventskeydown
,keyup
events from keyboard
Developer can use a few different ways to implement event handling to application.
- as a HTML attribute
onclick="..."
- as a DOM property
elem.onclick = function...
- as a Event listener
elem.addEventListener(event, handler[, phase])
A few examples
-
Add event handling with HTML attribute
1 2 3 4 5 6 7 8 9 10
<!-- all javascript code inline --> <button onclick="alert('You clicked me!')">Klikkaa</button> <!-- call own made function--> <p onclick="functionCallHere('You clicked me!')">Klikkaa</p> <script> function functionCallHere(text) { alert(text); } </script>
-
Event handing with DOM property
1
<button id="btn1">Klikkaa</button>
1 2 3 4 5
<script> btn1.onclick = function() { alert('You clicked me!'); } </script>
-
Event handling with event listeners.
1
<p id="elem">mouseover/mouseout/click?</p>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
<script> function fn1() { elem.style.backgroundColor = "yellow"; } function fn2() { elem.style.backgroundColor = "white"; } function fn3() { alert('You clicked me!'); }; elem.addEventListener("mouseover", fn1); // background yellow elem.addEventListener("mouseout", fn2); // background white elem.addEventListener("click", fn3); // alert </script>
-
this
keywork with events1
<p onclick="fn(this)">Click me?</p>
1 2 3 4 5
<script> function fn(elem) { elem.innerHTML = "You clicked me!"; } </script>
- Usually developer need more information about event content (where clicked etc..)
- Developer can find more detailed information inside a event object (like
[event.screenX, event.screenY]
or[event.keyCode]
)
- More details from event -
handleEvent
method will be called automatically.1
<p id="elem">Click and hold mouse button down</p>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class Selection { handleEvent(event) { switch(event.type) { case 'mousedown': elem.style.backgroundColor = "yellow"; elem.innerHTML = "mouse down X:" + event.screenX + "Y: " + event.screenY; break; case 'mouseup': elem.style.backgroundColor = "white"; elem.innerHTML = "Click and hold mouse button down"; break; } } } let selection = new Selection(); elem.addEventListener('mousedown', selection); elem.addEventListener('mouseup', selection);
Note
You can find a list of HTML Events here - HTML DOM Events
HTML form and events
- HTML form and fields has a lot of different propeties and events
- Developer can find a specific form using a following commands:
document.getElementById('formId')
,document.forms.formId
ordocument.forms[1]
which uses a form appearance number. - Form elements can be found using a
form.elements.fieldId
,form.fieldId
orform.elements[1]
- Form field properties can be used normally like
input.value
,select.value
,textarea.value
,input.checked
orselect.selectedIndex
, etc...
A few examples
-
Detect which checkbox is checked
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
<form> <input type="checkbox" name="number" value="12"> 12<br> <input type="checkbox" name="number" value="20"> 20<br> <input type="checkbox" name="number" value="53"> 53</br> <button id="btn">Click me!</button> </form> <script> function fn() { let form = document.forms[0]; // first and only form let numbers = form.elements.number; // All number elements if (numbers[2].checked) { // third number is checked // show alert with third value alert(numbers[2].value + " checked!"); } }; btn.addEventListener("click", fn); </script>
-
Read value from form component and show in
div
.1 2 3 4 5 6 7 8 9 10 11 12 13
<form id="form"> <input type="text" id="number"><br> <button type="button" onclick="showNumber(form.number.value)"> Show a number </button> </form> <div id="result"></div> <script> function showNumber(a) { var div = document.getElementById("result"); div.innerHTML = "Number is " + a + "<br>"; } </script>
-
Small example with
select
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
<select id="selection"> <option value="Select euros, Please!">Select euros</option> <option value="13">13 euros</option> <option value="31">31 euros</option> </select> <button onclick="show()"> Show selection </button> <div id="result"></div> <script> function show() { var div = document.getElementById("result"); div.innerHTML = selection.value; // selected value if (selection.selectedIndex == 1) { // second option is "selected" console.log("Wau you selected 13eur!"); } selection.options[0].selected = true; // change first one to "selected" } </script>