JavaScript note 05: DOM object

Posted by solodesignz on Mon, 24 Jan 2022 10:19:57 +0100

  • DOM, full name: Document Object Model
    • Document: represents the entire HTML web page document
    • Object: means to convert every part of the web page into an object
    • Model: use a model to represent the relationship between objects
  • Node: it is the most basic part of a web page. Every part of a web page can be called a node
    • Document node: entire HTML document
    • Element nodes: tags in HTML documents
    • Attribute nodes: attributes of elements
    • Text node: text content in label

Properties of nodes

nodeNamenodeTypenodeValue
Document node#document9null
Element nodeTag name1null
Attribute nodeAttribute name2Attribute value
Text node#text3Text content
<button id="btn">I'm a button</button>
<script type="text/javascript">
    // The browser has provided the document node object document
    // This object is the attribute of the window object and can be used directly in the page
    var btn = document.getElementById("btn");
    console.log(btn.innerHTML);
    btn.innerHTML = 'I am a Button';
</script>

Events are the interaction between users and browsers, such as clicking a button, moving the mouse, closing a window, etc

<!-- 
   You can set some in the properties corresponding to the event js Code, so that when the event is triggered, these codes will be executed
   This writing method couples structure and behavior, which is inconvenient for maintenance and is not recommended
-->
<button id="btn" onclick="alert('Disgusting~Why did you order me')">I'm a button</button>
<!-- 
    The event can be responded to in the form of a binding handler for the corresponding event of the button
    In this way, when the event is triggered, its corresponding function will be called
-->
<button id="btn">I'm a button</button>
<script type="text/javascript">
	var btn = document.getElementById("btn");
    // Bind a click event
    btn.onclick = function () {
        alert("Don't order~");
    };
</script>

Page loading

  • When the browser loads a page, it loads it from top to bottom, and runs one line after reading it
  • If the script tag is written to the top of the page, the page is not loaded when the code is executed, and the DOM object cannot be obtained at this time
  • The purpose of writing js code to the lower part of the page is to execute js code after the page is loaded
<button id="btn">I'm a button</button>
/*
	onload The event is triggered after the entire page is loaded
	Bind an onload event to the window, and the corresponding response function will be executed after the page is loaded
	This ensures that the page is loaded when the code executes
*/
window.onload = function () {
    var btn = document.getElementById("btn");
    // Bind a click event
    btn.onclick = function () {
    	alert("Don't order~");
    };
};

DOM query

1. Get the element node (called through the document object)

<div>
	<p>Which city do you like?</p>
	<ul id="city">
		<li id="bj">Beijing</li>
		<li>Shanghai</li>
		<li>Tokyo</li>
		<li>Seoul</li>
	</ul>
</div>
<div>
    gender:
    <input class="hello" type="radio" name="gender" value="male" />Male
    <input class="hello" type="radio" name="gender" value="female" />Female
    <br>
    <br>
    name:
    <input type="text" name="name" id="username" value="abcde" />
</div>

Get an element node object through the id attribute

window.onload = function () {
	// Get the node with id bj
	var r1 = document.getElementById("bj");
	console.log(r1.innerHTML); // Beijing
}

Gets a set of element node objects by tag name

window.onload = function () {
	// Get all li nodes
	var r2 = document.getElementsByTagName("li");
	for (let i = 0; i < r2.length; i++) {
		console.log(r2[i].innerHTML); // Beijing Shanghai Tokyo Seoul
	}
}

Get a set of element node objects through the name attribute

window.onload = function () {
	// Get all nodes with name=gender
	var r3 = document.getElementsByName("gender");
	for (let i = 0; i < r3.length; i++) {
		// innerHTML is not valid for self closing tags
    	// The attribute value of a node can be obtained by directly using the object to read the attribute
    	console.log(r3[i].value); // male female
    	// The class attribute cannot be used in this way
    	console.log(r3[i].className); // hello hello
	}
}

2. Obtain the child node of the element node (called through the specific element node)

<div>
	<p>Which city do you like?</p>
	<ul id="city">
		<li id="bj">Beijing</li>
		<li>Shanghai</li>
		<li>Tokyo</li>
		<li>Seoul</li>
	</ul>
	<p>Which character do you like?</p>
    <ul>
        <li>Feidu</li>
        <li>Sheng Wang</li>
        <li>Shen Lanzhou</li>
    </ul>
</div>

Gets the descendant node of the specified label name of the current node

window.onload = function () {
    var city = document.getElementById("city");
    var liList = city.getElementsByTagName("li");
    for (let i = 0; i < liList.length; i++) {
    	console.log(liList[i].innerHTML); // Beijing Shanghai Tokyo Seoul
    }
};

All child nodes of the current node

window.onload = function () {
    var city = document.getElementById("city");
    var childNodes = city.childNodes;
    // The childNodes property gets all nodes, including text nodes
    // At this time, the blank space between DOM tags will also be regarded as a text node (this behavior is not seen in IE8 and below)
    console.log(childNodes.length);// 9
    
    // The children attribute can get all the child elements of the current element
    var children = city.children;
    console.log(children.length); // 4
};

The first child node of the current node (the last child node uses last)

window.onload = function () {
    var city = document.getElementById("city");
    // The firstChild attribute gets the first child node (including blank text) of the current element
    var fChild = city.firstChild;
    console.log(fChild);// #text

    // The firstElementChild property gets the first child element of the current element (not supported by IE8)
    var firstElementChild = city.firstElementChild;
    console.log(firstElementChild.innerHTML);// Beijing
};

3. Get the parent node and brother node (call through specific nodes)

<div>
	<p>Which city do you like?</p>
	<ul id="city">
		<li id="bj">Beijing</li>
		<li>Shanghai</li>
		<li>Tokyo</li>
		<li>Seoul</li>
	</ul>
	<p>Which character do you like?</p>
    <ul>
        <li>Feidu</li>
        <li id="sw">Sheng Wang</li>
        <li>Shen Lanzhou</li>
    </ul>
</div>

Gets the parent node of the current node

window.onload = function () {
    var bj = document.getElementById("bj");
    var ul = bj.parentNode;
    console.log(ul.innerHTML);
    // innerText will automatically remove the label
    console.log(ul.innerText);// Beijing Shanghai Tokyo Seoul
};

Get the previous sibling node of the current node (next for the latter)

window.onload = function () {
    var sw = document.getElementById("sw");
    // It is also possible to get blank text
    var prev = sw.previousSibling;
    console.log(prev);// #text
    // Text not considered (not supported for IE8 and below)
    var prevElement = sw.previousElementSibling;
    console.log(prevElement.innerHTML);// Feidu
}

To get the content of a text node, you can use the nodeValue property

window.onload = function () {
	console.log(document.getElementById("bj").firstChild.nodeValue);// Beijing
};

4. Other query methods

Get body tag

window.onload = function () {
	var element = document.body;
	console.log(element);
};

Get html root tag

window.onload = function () {
	var element = document.documentElement;
	console.log(element);
};

Get all elements in the page

window.onload = function () {
	var element = document.all;
	console.log(element);
	element = document.getElementsByTagName("*");
	console.log(element);
};

Query a group of element node objects according to the class attribute value of the element

<div class="box1"></div>
<div class="box1"></div>
<div class="box1"></div>
window.onload = function () {
	var element = document.getElementsByClassName("box1");
	console.log(element.length);// 3 (IE9 and above support)
};

Query the element node object according to the CSS selector

<div class="box1">
	<div>Target element 1</div>
	<div>Target element 2</div>
	<div>Target element 3</div>
</div>
window.onload = function () {
	// An element node object that returns the first element found in the query
	var element = document.querySelector(".box1 div");
	console.log(element.innerHTML);// Target element 1
	// A set of element node objects
	element = document.querySelectorAll(".box1 div");
	console.log(element.length);// 3
	console.log(element[2].innerHTML);// Target element 3
};

DOM addition, deletion and modification

<div id="total">
	<div class="inner">
		<p>Which city do you like?</p>
		<ul id="city">
			<li id="bj">Beijing</li>
			<li>Shanghai</li>
			<li>Tokyo</li>
			<li>Seoul</li>
		</ul>
	</div>
</div>

Create and add child nodes

// Add a child element "Guangzhou" to the element with id city
window.onload = function () {
	// Create the element node object, and the parameter is the tag name string
	var li = document.createElement("li");
	// Create a text node object. The parameter is text content
	var gz = document.createTextNode("Guangzhou");
	// Adds a child node to the parent node
	li.appendChild(gz);
	var city = document.getElementById("city");
	city.appendChild(li);
};

Add a new node before specifying a node

// Add a child element "Guangzhou" before the element with id bj
window.onload = function () {
	var li = document.createElement("li");
	var gz = document.createTextNode("Guangzhou");
	li.appendChild(gz);
	// Add a new node before the specified node. Both belong to a parent node, and the method is called by the parent node
	// The first parameter is the new node to be added, and the second parameter is the specified node
	var city = document.getElementById("city");
	var bj = document.getElementById("bj");
	city.insertBefore(li, bj);
};

Replaces the specified node with a new node

// Replace the node with id bj with "Guangzhou"
window.onload = function () {
	var li = document.createElement("li");
	var gz = document.createTextNode("Guangzhou");
	li.appendChild(gz);
	// Replace the specified node with a new node. Both belong to a parent node, and the method is called by the parent node
	// The first parameter is the new node and the second parameter is the specified node
	var city = document.getElementById("city");
	var bj = document.getElementById("bj");
	city.replaceChild(li, bj);
};

Deletes the specified node

// Delete node with id bj
window.onload = function () {
	// Deletes the specified node, and the method is called by the parent node
	var city = document.getElementById("city");
	var bj = document.getElementById("bj");
	// city.removeChild(bj);
	bj.parentNode.removeChild(bj);
};

Manipulating CSS styles with DOM

1. Read and set inline style

<button id="btn01">Button</button>
<br><br>
<div id="box1"></div>
#box1 {
	width: 200px;
	height: 200px;
	background-color: red;
}
window.onload = function () {
	var btn01 = document.getElementById("btn01");
	btn01.onclick = function () {
		var box1 = document.getElementById("box1");
		/*
			The styles set and read through the style attribute are inline styles. Inline styles have higher priority and are often displayed immediately
			But if it is used in the style sheet! important. At this time, the style will have the highest priority and cannot be overwritten with JS
		*/
		// Modify the style of box1
		box1.style.width = "300px";
		box1.style.height = "300px";
		// Attributes with hyphens should be changed to hump nomenclature
		box1.style.backgroundColor = "yellow";
		// Read the style value of the element (also read the inline style)
		alert(box1.style.backgroundColor); // yellow
	};
};

2. Read the currently effective style

window.onload = function () {
	var btn01 = document.getElementById("btn01");
	btn01.onclick = function () {
		var box1 = document.getElementById("box1");
		/*
			Read box1 the style currently in effect
			If the style is not set for the current element, the default value of the style is returned
			Only IE supports
		*/
		// At this time, the obtained styles are read-only
		alert(box1.currentStyle.width);// 200px
		
		/*
			The first parameter is the element to get the style, and the second can pass a pseudo element
			If the obtained style is not set, the true value of the style is returned
			IE8 And below are not supported
		*/
		var obj = getComputedStyle(box1, null);
		alert(obj.width);// 200px
		
		// Browser compatible ways to get styles
		alert(getStyle(box1, "width"));// 200px
	};

	// First parameter: the element to get the style
	// Second parameter: the style name to get
	function getStyle(obj, name) {
		if (window.getComputedStyle) {
			return getComputedStyle(obj, null)[name];
		} else {
			return obj.currentStyle[name];
		}
	}
};

3. Other style related attributes

Properties are read-only and cannot be modified

<button id="btn01">Button</button>
<br><br>
<div id="box4">
	<div id="box5"></div>
</div>
<br><br>
<div id="box2" style="position: relative;">
	<div id="box1"></div>
</div>
#box1 {
	width: 200px;
	height: 200px;
	background-color: red;
	padding: 10px;
	border: 10px solid rosybrown;
}

#box2 {
	background-color: yellow;
	padding: 100px 150px;
}

#box4 {
	width: 300px;
	height: 300px;
	background-color: turquoise;
	overflow: scroll;
}

#box5 {
	width: 450px;
	height: 600px;
	background-color: tomato;
}

Gets the height and width of the element (content area + inner margin)

window.onload = function () {
	var box1 = document.getElementById("box1");
	var btn01 = document.getElementById("btn01");
	btn01.onclick = function () {
		alert(box1.clientWidth);// 220
		alert(box1.clientHeight);// 220
	};
};

offset

window.onload = function () {
	var box1 = document.getElementById("box1");
	var btn01 = document.getElementById("btn01");
	btn01.onclick = function () {
		// Get the height and width of the whole element (content area + inner margin + border)
		alert(box1.offsetWidth);// 240
		alert(box1.offsetHeight);// 240
		// Gets the nearest ancestor element that has enabled positioning from the current element. If all ancestor elements have not enabled positioning, body is returned
		alert(box1.offsetParent.id);// box2
		// Gets the offset of the current element from its parent element
		alert(box1.offsetTop);// 100
		alert(box1.offsetLeft);// 150
	};
};

scroll

window.onload = function () {
	var box1 = document.getElementById("box1");
	var box4 = document.getElementById("box4");
	var btn01 = document.getElementById("btn01");
	btn01.onclick = function () {
		// Gets the width and height of the entire scrolling area of the element
		alert(box4.scrollHeight);// 600
		alert(box4.scrollWidth);// 450
		// Scroll bar scrolling distance
		alert(box4.scrollLeft);
		alert(box4.scrollTop);
		// scrollHeight - scrollTop = clientHeight the scroll bar scrolls to the bottom
		// scrollWidth - scrollLeft = clientWidth the scroll bar scrolls to the far right
	};
};