Magren

Magren

Idealist & Garbage maker 🛸
twitter
jike

The DOM of HTML and the BOM of the browser.

Record the knowledge points you have recently learned.

HTML DOM (Document Object Model)#

Overview: When a web page is loaded, the browser creates the Document Object Model (DOM) of the page.

Finding HTML Elements#

Usually, HTML elements can be manipulated using JavaScript.

To do this, you must first find the element. There are three methods to do this:

  • Find HTML element by id: var x = document.getElementById("intro");
  • Find HTML elements by tag name: var y = document.getElementsByTagName("p");
  • Find HTML elements by class name: var x = document.getElementsByClassName("intro");

Changing HTML Content#

Use the innerHTML property.

<html>
<body>

<p id="p1">Hello World!</p>

<script>
document.getElementById("p1").innerHTML = "New text!";
</script>

</body>
</html>

Changing HTML Style#

Use the style property.

<body>
 
<p id="p1">Hello World!</p>
<p id="p2">Hello World!</p>

<script>
document.getElementById("p2").style.color = "blue";
document.getElementById("p2").style.fontFamily = "Arial";
document.getElementById("p2").style.fontSize = "larger";
</script>

</body>

Using Events#

<body>

<h1 id="id1">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color='red'">
Button</button>

</body>
Defining Functions and Binding Events in JavaScript
var func = function () {
                alert("hello world")
            }
var aa = document.getElementById('vv')
aa.onclick = func
Using addEventListener
document.getElementById('vv').addEventListener('click', func);


document.getElementById('vv').addEventListener('click', function () {
           alert('hahah')
        })

onload and onunload Events#

  • The onload and onunload events are triggered when the user enters or leaves the page.
  • The onload event can be used to detect the visitor's browser type and browser version, and load the correct version of the web page based on this information.
  • The onload and onunload events can be used to handle cookies.
<body onload="checkCookies()">

<script>
function checkCookies(){
	if (navigator.cookieEnabled == true){
		alert("Cookies are enabled")
	}
	else{
		alert("Cookies are disabled")
	}
}
</script>
	
</body>

onchange Event#

The onchange event is often used in combination with input field validation.

<!-- The function is called when the content of the input field changes and the focus is moved away from the input field -->
<input type="text" id="fname" onchange="upperCase()">

onmouseover, onmouseout, onmousedown, onmouseup Events#

  • onmouseover: Triggered when the mouse is moved over an HTML element.
  • onmouseout: Triggered when the mouse is moved away from an HTML element.
  • onmousedown: Triggered when the mouse button is pressed down on an element.
  • onmouseup: Triggered when the mouse button is released.

HTMLCollection Object#

Overview: The getElementsByTagName() method returns an HTMLCollection object. The HTMLCollection object is similar to an array that contains HTML elements. Elements in the collection can be accessed using an index (starting from 0).

var x = document.getElementsByTagName("p");
y = x[1];   // Access the second p element

NodeList Object#

Overview: The NodeList object is a collection of nodes (elements) obtained from the document.

Use the querySelectorAll property to obtain the object.

var myNodeList = document.querySelectorAll("p");

Access elements using the index method as well.

Difference Between NodeList and HTMLCollection#

  • HTMLCollection elements can be accessed by name, id, or index.
  • NodeList can only be accessed by index.
  • Only the NodeList object contains attribute nodes and text nodes.

Browser Object Model (BOM)#

This object represents the browser window, and global variables are properties of the window object. Global functions are methods of the window object (including document).

Window Size#

  • window.innerHeight - the inner height of the browser window (including scrollbars)
  • window.innerWidth - the inner width of the browser window (including scrollbars)

Window Screen#

  • screen.availWidth - the available width of the screen
  • screen.availHeight - the available height of the screen

Window Location#

  • location.hostname returns the domain name of the web host
  • location.pathname returns the path and filename of the current page
  • location.port returns the port of the web host (80 or 443)
  • location.protocol returns the web protocol being used (http: or https:)
  • location.href returns the URL of the current page
  • location.assign(url) loads a new HTML document specified by the URL. It is similar to a link, redirecting to the specified URL. The current page will be replaced with the new page content, and you can click the back button to return to the previous page.
  • location.replace(url) replaces the current document with the one specified by the URL. This method replaces the current window page, so there is no back button to return to the previous page.

Window History#

  • history.back() - equivalent to clicking the back button in the browser
  • history.forward() - equivalent to clicking the forward button in the browser

In terms of forward and backward functionality, it can also be achieved using the history.go() method

history.go(1);  // go() with a parameter of 1 means go forward one page
history.go(-1);  // go() with a parameter of -1 means go back one page
history.go(0);  // go() with a parameter of 0 means refresh the page

Pop-up Windows#

Alert Box

alert()

alert("Alert box!");
Confirm Box

confirm()

var r = confirm("Press a button");
if (r == true) {
    x = "You pressed OK!";
} else {
    x = "You pressed Cancel!";
}
Prompt Box

prompt() - When the prompt box appears, the user needs to input a value and then click OK or Cancel to continue.

var person = prompt("Please enter your name");
if (person != null && person != "") {
    document.getElementById("demo").innerHTML = person;
}

JavaScript Timing Events#

  • setInterval() - repeatedly executes a specified code every specified number of milliseconds. It takes two parameters: the function to be executed and the number of milliseconds.
  • setTimeout() - executes a specified code after a specified number of milliseconds. It takes two parameters: the function to be executed and the number of milliseconds.

Methods to stop the timing: clearInterval() and clearTimeout()

var myVar = setInterval(function(){myTimer()}, 1000);
function myTimer() {
   alert("Hello");
}
function myStopFunction() {
    clearInterval(myVar);
}


var myVar;
function myFunction() {
    myVar = setTimeout(function(){alert("Hello")}, 3000);
}
function myStopFunction() {
    clearTimeout(myVar);
}

Cookies#

Overview: Cookies are data stored in a text file on your computer. They are stored as key-value pairs.

document.cookie = "username=John Doe; expires=Thu, 18 Dec 2043 12:00:00 GMT"; //expires is the expiration time of the cookie, by default, the cookie is deleted when the browser is closed
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2043 12:00:00 GMT; path=/"; //the path parameter tells the browser the path of the cookie. By default, the cookie belongs to the current page.
var x = document.cookie;
document.cookie = "username=John Smith; expires=Thu, 18 Dec 2043 12:00:00 GMT; path=/"; //similar to creating, it directly overwrites the existing cookie
Retrieving Cookies

If a new cookie is set, the old cookie will not be overwritten. The new cookie will be added to document.cookie. So, if you re-read document.cookie, you will get the following data:
cookie1=value; cookie2=value;

function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for(var i = 0; i < ca.length; i++) {
    var c = ca[i].trim();
    if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
  }
  return "";
}
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.