JavaScript: Browser Integration DOM
Page 10
Browser Integration DOM
Introduction
JavaScript browser integration combines HTML Web page elements with JavaScript programming. Web page elements display to the Web browser window. JavaScript programming reacts to, or modifies, Web page elements dynamically. In other words, JavaScript browser integration allows JavaScript to interact with HTML markup.
Learn Document Object Model(DOM) methods and properties on this page, including many techniques to access HTML elements, HTML collections and node lists. Learn to add and remove event handlers including animation events and context menu events. Traverse with DOM navigation and nodes. Learn to modify, or add, elements, text and styles.
Browser Integration
Developers may use both the Browser Object Model (BOM) and the Document Object Model (DOM). BOM doesn't include standardized features, however most browsers apply similar BOM properties and methods. Learn about the BOM, on the previous page. Learn about the DOM here.
DOM
The Document Object Model (DOM), is a World Wide Web Consortium (W3C) standard. That means we can expect all compliant browsers to maintain DOM features.
With the DOM, JavaScript developers can modify, delete, add and respond to all HTML elements and attributes on a Web page. The DOM also allows programmers to modify CSS styles of elements on the page.
The DOM includes HTML elements, properties, methods and event handlers.
Access HTML Elements
JavaScript developers can access HTML elements by identifier,
tag name, class name, anchors, body, embeds,
forms and images.
These lists are also called HTML collections.
Their type is an HTMLCollection
not an array.
Yet you may use the property, length
,
to iterate over the collection, similar to an array.
Just remember an HTMLCollection
contains
HTML elements with many DOM features.
Access HTML Element by ID
let e = document.getElementById( 'elementID' );
Access HTML Elements By Tag Type
eTags = document.getElementsByTagName( 'tagname' );
Access HTML Elements By Class
eClass = document.getElementsByClassName( 'classname' ); b = document.getElementsByClassName( "box" ); alert(b[0]);
Access By Other Tags
Access HTML elements with other tags as well, such as
document.anchors
,
document.body
,
document.embeds
,
document.forms
and
document.images
.
Access Anchor & Area Tags
Obtain all anchor tags and area tags with
document.links
property.
Tap a Box: Access HTML Elements
The Access By Class Name
box,
obtains all elements by the class name box
.
The inner HTML of each box is then copied to
the Access By Class Name
box.
The box I'm using to display returned values,
has a class name of bx
, instead of box
.
Otherwise there's a problem where JavaScript writes
the inner HTML of each box, including the
Access By Class Name
box.
This would happen after JavaScript
has already copied the inner HTML of previous
boxes to the Access By Class Name
box.
Therefore you'd end up with
copies of the inner HTML from each box.
Does that make sense to you? I hope so. Code
would repeat the text of previous boxes, while
copying the text of the Access By Class Name
box.
See function getByClassName()
in JavaScript file,
access.js.
Access By ID
function getByID(id){ let byID = document.getElementById( id ); let s = "JavaScript accesses this box by ID."; byID.innerHTML = s; }
Access By Tag Type H3
function getByTag(){ let byTag = document.getElementById( 'byTag' ); let aH3 = document.getElementsByTagName( 'H3' ); let j = aH3.length; byTag.innerHTML = ""; for (i = 0; i < j; i++){ byTag.innerHTML += aH3[i].innerHTML+"<br><br>"; } }
Access By Class Name
function getByClassName(){ let byClass = document.getElementById( 'byClass' ); let aBoxes = document.getElementsByClassName( 'box' ); let j = aBoxes.length; byClass.innerHTML = "Boxes On This Page:<br>"; for (i = 0; i < j; i++){ byClass.innerHTML += aBoxes[i].innerHTML+"<br><br>"; } }
Access By Images
function getByImage(){ let byImg = document.getElementById( 'byImg' ); let aImages = document.images; let j = aImages.length; byImg.innerHTML = ""; for (i = 0; i < j; i++){ byImg.innerHTML += aImages[i].src+"<br><br>"; } }
Access All Scripts
Obtain all page scripts with
document.scripts
.
Access Node Lists
The querySelectorAll()
method returns
a NodeList
. Node lists are quite
different than HTML collections.
let b = document.querySelectorAll( "div.box" );
HTMLCollection Versus NodeList
Similarities
Both HTMLCollection
and NodeList
have a length
property.
You can iterate over either type.
You can access elements by index number.
Differences
Elements in an HTMLCollection
can be accessed by name or ID.
Elements in a NodeList
cannot.
Elements in an NodeList
can include attribute and text nodes.
Elements in an HTMLCollection
cannot.
Tap a Box
See the source code for getByScript()
and getByQuery()
,
access.js.
Access By Scripts
function getByScript(){ let byScript = document.getElementById( 'byScript '); let aScripts = document.scripts; let j = aScripts.length; let i = 0; byScript.innerHTML = "Scripts For This Page:<br>"; for (i = 0; i < j; i++){ byScript.innerHTML += aScripts[i].src+"<br><br>"; }
Access By Query Selector
function getByQuery(){ let byQuery = document.getElementById( 'byQuery' ); let aSpans = document.querySelectorAll( "img.toc" ); let j = aSpans.length; let i = 0; let s = "Query Selector, img.toc. See span.img.src:<br>; byQuery.innerHTML = s; for (i = 0; i < j; i++){ byQuery.innerHTML += aSpans[i].src+"<br><br>"; } }
HTML Properties
The HTML DOM includes the following independent properties. See the Change Page Title box below, for one example. Access other properties with similar techniques.
document.strictErrorChecking, document.URL, document.referrer, document.lastModified, document.inputEncoding, document.implementation, document.title
Change HTML Content
Change the content of individual HTML elements with
the innerHTML
property, as follows.
e.innerHTML = "Changed Element Content";
If the HTML element is an input
type,
then change the content as follows.
e.value = "Changed Input Content";
Change HTML Attribute
The following examples also allow you to assign values to attributes, referenced in the BOM section on the previous page.
e.attribute = "new value"
Alternatively change the attribute's value as follows.
a.setAttribute( attributeName, valueName );
The following code obtains an image, by ID,
then change's the image's src
value
to display a different image.
im = document.getElementById( "imgYellow" ); im.src="https://7thunders.biz/thumbnails/color-blue.png";
Alternatively change the image's src
as follows.
a.setAttribute( 'src', 'https://7thunders.biz/thumbnails/color-gold.png' );
Tap Boxes: Change Attribute, Title
function changeSrc(){ let byAtt = document.getElementById( 'byAtt' ); byAtt.setAttribute( 'src', 'https://7thunders.biz/thumbnails/color-violet-lt.png' ); }
Change Page Title
function changeTitle(id){ let byTitle = document.getElementById( id ); let t = "Changed Title"; let s = "<p>Document Title Changed to<br><q>" +t+"</q></p>"; byTitle.innerHTML = s; document.title=t; }
Change HTML Style Property
e.style.property = "new style"
Tap Boxes: Change Style Property, Create Append Element
Change Style Property
function changeStyleProp(id){ let st = document.getElementById( id ); s = "red"; st.style.backgroundColor = s; }
Create Element
function changeEl(id){ let chEl = document.getElementById( id ); let p = document.createElement( 'p' ); let s = "New element appended and created."; chEl.appendChild(p); p.innerHTML = s; }
Delete HTML Element
document.removeChild(e)
Replace HTML Element
document.replaceChild(eSrc, eDest)
Output Text to HTML Document
document.write("Hello World")
DOM Event Handlers
Event handlers respond to page and user response, such as clicking a button or swiping an image. The DOM includes a wide array of event handlers.
Assign an event listener with
addEventListener(...)
or within the
HTML element itself, such as the following:
<p onclick="myClickFunction()">
Remove an event listener with
removeEventListener(...)
or assign
null
to the name of the event listener.
Bubbles or Capture
The addEventListener(...)
method's
last parameter represents capturing. When
assigned the default, false
, then
events are handled with bubbling. When
assigned, true
, then events are
handled with capturing.
Bubbling allows inner event listeners to handle an event before outer event listeners. Capturing allows outer event listeners to handle an event before inner event listeners.
As you can see with the following test, sometimes
inner event handlers don't activate with captures.
The outer capD
element activates whether
you tap the outer capD
or the inner capP
,
paragraph element.
You can see the
JavaScript: Capture Versus Bubble
code below, or
the entire JavaScript file,
events.js.
Output:
bubDfor Bubbles.
Tap Paragraph bubP
for Bubbles.
capDfor Captures.
Tap Paragraph capP
for Captures.
JavaScript: Capture Versus Bubble
/** * Access a set of elements from this * web page. * The first set receive default bubbling * onclick event handlers. * The second set receive capturing * onclick event handlers. */ function assignBubbles(){ let bubD = document.getElementById( 'bubD' ); let bubP = document.getElementById( 'bubP' ); bubD.addEventListener( 'click', clickedBC ); bubP.addEventListener( 'click', clickedBC ); let capD = document.getElementById( 'capD' ); let capP = document.getElementById( 'capP' ); capD.addEventListener( 'click', clickedBC, true ); capD.addEventListener( 'click', clickedBC, true ); bubOuput = document.getElementById( 'bubOuput' ); } /** * Activate when an element * is clicked. * @param e: Event handler. * The currentTarget is the activated * HTML element. The id equals * bubD,bubP,capD,capP representing * bubbling and capturing outer DIV * elements and inner paragraph elements. */ function clickedBC(e){ let cTarget = e.currentTarget; let id = e.currentTarget.id; let s= "You clicked me."+cTarget+","+id"; bubOutput.innerHTML += s; }
DOM Event Handlers: Previously Covered
See previous Event Attributes
examples with code, in the HTML Elements
set of tutorials.
Previous examples implement the following DOM
event handlers,
onafterprint(), onbeforeprint,
onbeforeunload(), onload(),
ontouchcancel, ontouchstart(),
ontouchend(), onblur(), onfocus(),
oninput(), oninvalid(), onselect(),
onsubmit(),
onclick(), ondblclick(),
onmousedown(), onmousemove(), onmouseout(), onmouseover(),
onmouseup(), onwheel(),
ondrag(), ondragend(), ondragenter(),
ondragleave(), ondragover(), ondragstrt(),
ondrop(), onscroll(),
oncopy(), oncut(), onpaste(),
oncanplay(), oncanplaythrough(),
onemptied(), onended(), onerror(),
onloadeddata(), onloadedmetadata(),
onpause(), onplay(), onplaying(), onprogress(),
onseeked(), onseeking(), onsuspend(),
ontimeupdate(), onvolumechange()
and
ontoggle(),
DOM Event Handlers: This Page
This section provides examples and source code
for the following event handlers,
change(), contextmenu(),
animationend(), animationinteration(), animationstart(),
fullscreenchange(), fullscreenerror(),
hashchange(), keydown(), keypress(), keyup(), message(),
offline(), online(),
pagehide(), pageshow(), popstate(),
ratechange(), reset(), search(),
show(), stalled(), timeupdate(),
transitionend(),
and waiting()
.
Event Handler Menus: Context, Select
Tap a Box: Context Menu, Select Option
Read code below, or load the JavaScript file, events.js.
Hide or show context menu. Right click or long click.
function getSelectOption(n) { let id = document.getElementById( n ); var s = id.value; var ps = document.getElementById( 'ps' ); ps.innerHTML = "You Selected: " +s; }
Code for Context Menu
The following few sections include the HTML markup, JavaScript and CSS rule sets for the menu example.
HTML Markup: Context Menu
When the Web body loads, create
the menu. Also assign
oncontextmenu="return false;"
,
which prevents the default context
menu from displaying.
Then create an element, in this case it's
a div
.
Assign oncontextmenu="menuActivate()"
.
See function menuActivate()
,
declared with JavaScript, below.
Assign the ID of the menu.
In this case JavaScript gives the
menu an ID of m
.
I added a paragraph for displaying information
during debugging, with an ID of pSD
.
The element containing the context menu
has an id of boxSD
.
<body onload="makeMenu()" oncontextmenu="return false;" > ... <div class="box bu" id="boxSD" oncontextmenu="menuActivate()" > <p id="pSD" >Click the button then right click to see the menu. </p> </div>
JavaScript: Context Menu
Create the menu, once when the Web body loads,
with function
makeMenu()
.
Whenever the user right clicks, or long clicks, the box call
menuActivate()
which executes menuShowHide()
,
passing variable dShow
,
as its ownly parameter.
Alternate values for dShow
.
When dShow == 'block'
, the
menu displays.
When dShow == 'none'
the
menu hides.
// Variables for the // menu box, menu and menu items. var boxSD, pSD = null; var menu = menuItem0 = null; var menuItem1 = menuItem2 = null; // Alternates between // 'none' and 'block'. var dShow = 'none'; /** When the Web page body loads, create the menu. No parameters. */ function makeMenu(){ boxSD = document.getElementById( 'boxSD' ); pSD = document.getElementById( 'pSD' ); menu = document.createElement( 'menu' ); menu.id='m'; menu.type = 'context'; menu.style.width='50%'; boxSD.appendChild(menu); menuItem1 = document.createElement( 'menuItem' ); let s1 = "<a href='javascript10.php'>Reload</a>"; menuItem1.innerHTML = s1; menuItem2 =document.createElement( 'menuItem' ); let s2 = "<a href='mailto:Support@7Thunders.biz'>Send Email</a>"; menuItem2.innerHTML = s2; boxSD.appendChild(menu); menu.appendChild(menuItem1); menu.appendChild(menuItem2); menuShowHide(dShow); } /** Called when the user right clicks on the div box. No parameters. */ function menuActivate(){ menuShowHide(dShow); } /** Show and hide the menu and menu items based no @param d: 'block' or 'none' */ function menuShowHide(d){ menu.style.display = menuItem1.style.display = d; menuItem2.style.display = d; if(d == 'block')d = 'none'; else d = 'block'; // Save the last display option: dShow = d; }
Context Menu: Styles
I added some simple rule-sets to style the anchors in the menu item without underlines.
menu{ width:100%; } menuItem{ display:block; clear:both; text-align:left; width:98%; padding:1%; color:white; background-color:aqua; border:solid 1px white; } menuItem a, menuItem a:link, menuItem a:visited, menuItem a:hover, menuItem a:active { color:white; text-decoration:none; }
Option Menu: HTML Markup
This section displays the HTML markup for the simple option menu.
For JavaScript, see either the full JavaScript file, events.js, or the Select Option box, above.
<select id="sel" onchange="getSelectOption('sel')" > <option onclick="getSelectOption('sel')"> Prairie Dogs</option> <option onclick="getSelectOption('sel')"> Prairie Dogs</option> <option onclick="getSelectOption('sel')"> Pronghorn</option> <option onclick="getSelectOption('sel')"> Moutain Lions</option> </select> <p id="ps"></p>
Not Supported or Useful
The onopen()
event handler's
only defined for image elements and currently
supported on few browsers.
The onabort
event handler's not
recommended.
The durationchange
and onloadstart
events apply to audio and video elements
only, with minimal uses.
The duration changes from NaN
to the length of the media, once only,
after the media loads.
The focusin
and focusout
event listeners don't activate in all browsers.
Animation Events
The Tap Starts Animation
box demonstrates CSS3 animation with
JavaScript animationstart, animationend
and animationiteration
event handlers.
Tap the box and the animation starts.
For each iteration of the animation, a count increments
and displays. Animation Ended
displays when
the animation completes.
See below for JavaScript: Animation Events
source code.
See the CSS3 Animation, below.
Most of all see the interactive box titled,
Tap Starts Animation.
Tap for Examples
Tap Starts Animation
Tap for Message
CSS3 Animation
The following rule-sets declare animated colors which iterate four times. You may also see the style sheet itself, anim.css.
.tanim { animation:tAnim 3s 4; -webkit-animation:tAnim 3s 4; animation-fill-mode: forwards; } @keyframes tAnim { 0% { background-color:blue; } 20% { background-color:green; } 40% { background-color:yellow; } 60% { background-color:red; } 80% { background-color:violet; } 100% { background-color:blue; } }
JavaScript: Animation Events
/** * Tap the * "Tap Starts Animation" box * to activate animStart(). */ function animStart(){ if (anim == null){ anim = document.getElementById( 'anim' ); } // Assign our box element class // and the animaton CSS3 class. anim.className = "box tanim"; anim.style.animationPlayState="running"; anim.style.webkitAnimationPlayState="running"; // Activates when // CSS animation starts: anim.addEventListener( "webkitAnimationStart", animStarted ); anim.addEventListener( "animationstart", animStarted ); // Activates when // CSS animation ends: anim.addEventListener( "webkitAnimationEnd", animEnd ); anim.addEventListener( "animationend", animEnd ); // Activates when CSS animation // begins to rerun sequence: anim.addEventListener( "webkitAnimationIteration", animIterate ); anim.addEventListener( "animationiteration", animIterate ); } /** * Activates when our CSS3 * animation begins. */ function animStarted(){ nCount = 1; anim.innerHTML = "Animation Started"; } /** * Activates when our CSS3 * animation ends. */ function animEnd(){ anim.innerHTML = "Animation Ended"; } /** * Activates for each complete * cycle of our CSS3 defined * animation. * Displays which cycle we're on. */ function animIterate(){ let s = "Animation Iterated: " + nCount; anim.innerHTML = s; nCount++; }
Miscellaneous Events
Some miscellaneous events include server side events (SSE) and pop states
SSE
Click the Tap for Message box, above. A server side event (SSE) should respond. However I believe shared server settings with HostGator currently cause some issues. Shared server hosting usually allows one way, outward connections. Therefore perhaps I need to find the solution.
You'll probably see the
message EventSource failed.
.
See the source code for SSE PHP.
See output from the PHP
file itself.
Pop States
See below for JavaScript: PopState source code. Also select the Tap to enable PopState box, then leave the page or change your browsing history.
Tap to enable PopState
Tap to disable PopState
JavaScript: PopState
/** * Activated with back button, * and navigation events. */ function assignPopState(){ window.onpopstate = getPopState; } /** * Remove the pop state event * handler. You won't see an * alert box when you leave * the page. */ function removePopState(){ window.onpopstate = null; } /** * Must use alert box * if navigating away from window. * Otherwise users won't see * the message. * @param e: Event object */ function getPopState(e){ alert("Pop State: "+e.toString()); }
SSE PHP
The following PHP should display the server's time. See the SSE PHP yourself.
<?php header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); header('Access-Control-Allow-Origin: https://code.7thunders.biz'); $time = date('r'); echo "data: The server time is: {$time}\n\n"; flush(); ?>
DOM Event Properties
See Event Elements:: CSS3 Animation
for code, with a different use for the
animPlayState
property.
See commonly accessed event properties, with event handlers,
in the source code applied to this page in JavaScript file,
events.js.
Also document.readyState
allows developers
to determine if an HTML page is still loading, some features are available
or its completed loading.
DOM Navigation
DOM navigation consists of three types of nodes. The types include document, element and text. Attribute nodes are deprecated. The document node is the root, or top, element for the HTML DOM. Consider the DOM like an upside down tree, with the root at the top. All other nodes are like leaves on branches. However a leaf can have only one parent. A parent can have multiple children. Therefore leaves can have a number of siblings.
You've already seen how to access nodes by ID.
You can also access multiple childNodes
.
You can access each childNode's
value with the nodeValue
property,
if it exists.
Tap either box below.
Each box navigates the node tree.
Notice that not every node has
a nodeValue
, yet it
might have innerHTML
values,
if it's a text node.
getChildNode('getnode1','c3',0)
function getChildNode( idoutput, idinput, n ) { let eout = document.getElementById( idoutput ); let ein = document.getElementById( idinput ); let c = ein.childNodes[n]; if(c.nodeValue != null){ eout.innerHTML = c.nodeValue; } else if(c.innerHTML != null){ eout.innerHTML = c.innerHTML; } }getChildNode('anim',1)
function getChildNode( idoutput, idinput, n ) { let eout = document.getElementById( idoutput ); let ein = document.getElementById( idinput ); let c = ein.childNodes[n]; if(c.nodeValue != null){ eout.innerHTML = c.nodeValue; } else if(c.innerHTML != null){ eout.innerHTML = c.innerHTML; } }
Properties
Nodes have three properties nodeType, nodeName
and nodeValue
.
Not all nodes have a nodeValue
.
You've already seen how
to use nodeValue
, when it exists.
Values of nodeType
include
text, elements, comments, documents, document types
and the deprecated attribute.
The nodeName
property represents
an HTML tag name, such as P
or DIV
.
Traversal
You can travel through an HTML document tree
with nodes.
Property parentNode
allows you to
travel up a tree.
Properties childNodes, lastChild
and firstChild
allow you to travel down, or up, a tree.
Properties nextSibling
and
previousSibling
allow you to travel
laterally amongst equal level leaves
on a tree.
You can also count childNodes
in arrays and
visit every leaf on a tree. Consider recursion for efficient node traversal.
DOM Nodes
Easily create HTML elements and add elements to other elements, or the document itself, with JavaScript.
Create HTML Element
The following code creates a new paragraph, including the opening and closing tags.
let p = document.createElement('p')
Add Text
The following line creates a text node.
let s = 'Add some text.'; let n = document.createTextNode( s );
Append HTML Element
Don't forget to add the text to your paragraph, then add the paragraph to your document, as follows.
p.appendChild(n); document.appendChild(p);
JavaScript: Create,Append Elements
/** * Create a paragraph * @param:sText string for * paragraph content. * @return: return the paragraph. */ function addPH(sText){ let p = document.createElement( 'p' ); let n = document.createTextNode( sText ); p.appendChild(n); return p; } /** * Create a list with list items. * @param:a,b,c strings for list items. * @return: return the list. */ function addList(a,b,c){ let o = document.createElement( 'ol' ); let l1 = document.createElement( 'li' ) let l2 = document.createElement( 'li' ) let l3 = document.createElement( 'li' ); let a1 = document.createTextNode( a ); let b2 = document.createTextNode( b ); let c3 = document.createTextNode( c ); o.appendChild(l1); l1.appendChild(a1); o.appendChild(l2); l2.appendChild(b2); o.appendChild(l3); l3.appendChild(c3); return o; }
Summary
JavaScript browser integration combines HTML Web page elements with JavaScript programming. Web page elements display to the Web browser window. JavaScript programming reacts to, or modifies, Web page elements dynamically. In other words, JavaScript browser integration allows JavaScript to interact with HTML markup.
You learned Document Object Model(DOM) methods and properties on this page, including many techniques to access HTML elements, HTML collections and node lists. You learned to add and remove event handlers including animation events and context menu events. You can traverse an HTML page with DOM navigation and nodes. You learned to modify, or add, elements, text and styles.
Learn JavaScript
JavaScript's the foundation of Web developer and Website design skills. This free and unique JavaScript tutorial includes some new or seldom used, but useful features.