Solution: Know Your Browser
Exercise solution to "Know Your Browser." where the solution leverages DOM and BOM to create a final webpage with all specified information
We'll cover the following...
Solution
The final solution to the problem is here.
The above solution shows that we do not alter any elements on HTML directly. Instead, use JavaScript to add/remove elements to DOM and fetch certain information through BOM. Let’s see more detail below.
Press + to interact
// delete all elements with h2 tagvar del1 = document.getElementsByTagName('h2');for(var i = 0; i < del1.length; i++){del1[i].parentNode.removeChild(del1[i]);}// delete all elements with p tagvar del2 = document.getElementsByTagName('p');for(var i = 0; i < del2.length; i++){del2[i].parentNode.removeChild(del2[i]);}// Adding browser namevar browserEle = document.getElementById('browserName');browserEle.firstChild.nodeValue = 'Browser name: ' + window.navigator.appName;// Adding area of outer window sizevar areaEle = document.getElementById('windowSize');areaEle.firstChild.nodeValue = 'Area of the window: ' + (window.outerHeight * window.outerWidth);// URL information elementvar newEle1 = document.createElement('p');var content1 = document.createTextNode(`HostName: ${window.location.hostname}\n`);newEle1.appendChild(content1);// full urlvar newEle2 = document.createElement('p');var content2 = document.createTextNode(`URL: ${window.location.href}\n`);newEle2.appendChild(content2);// Add to bodyvar body = document.getElementById('target');body.appendChild(newEle1); // add hostNamebody.appendChild(newEle2); // add URL
In the above code, do the following.
-
Delete elements with tag names
'p'
and'h2'
. The HTML page shows that these elements should be deleted. But do the following for both:-
Fetch all elements with tag names for
'h2'
(line 2) and'p'
(line 7) withdocument.getElementsByTagName
method. -
Because of a
NodeList
, iterate the list using afor
loop for both. ...
-