...

/

Solution: Know Your Browser

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.

Console

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 tag
var del1 = document.getElementsByTagName('h2');
for(var i = 0; i < del1.length; i++){
del1[i].parentNode.removeChild(del1[i]);
}
// delete all elements with p tag
var del2 = document.getElementsByTagName('p');
for(var i = 0; i < del2.length; i++){
del2[i].parentNode.removeChild(del2[i]);
}
// Adding browser name
var browserEle = document.getElementById('browserName');
browserEle.firstChild.nodeValue = 'Browser name: ' + window.navigator.appName;
// Adding area of outer window size
var areaEle = document.getElementById('windowSize');
areaEle.firstChild.nodeValue = 'Area of the window: ' + (window.outerHeight * window.outerWidth);
// URL information element
var newEle1 = document.createElement('p');
var content1 = document.createTextNode(`HostName: ${window.location.hostname}\n`);
newEle1.appendChild(content1);
// full url
var newEle2 = document.createElement('p');
var content2 = document.createTextNode(`URL: ${window.location.href}\n`);
newEle2.appendChild(content2);
// Add to body
var body = document.getElementById('target');
body.appendChild(newEle1); // add hostName
body.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:

    1. Fetch all elements with tag names for 'h2' (line 2) and 'p' (line 7) with document.getElementsByTagName method.

    2. Because of a NodeList, iterate the list using a for loop for both. ...