3. Silicon Valley-JavaScript Foundation-Li Lichao-DOM

1. What is DOM

  • DOM, full name Document Object Model Document Object Model
  • JS uses DOM to manipulate HTML documents, so long as you understand DOM, you can manipulate WEB pages as you like.
  • File
    • Represents a real HTML Web page document
  • object
    • That means converting every part of a Web page into an object
  • Model
    • Use models to represent the relationships between objects so that we can get them easily.

2. Model

3. Nodes

  • Node is the most basic component of our web page. Each part of a web page can be called a node
  • For example: HTML tags, attributes, text, comments, this document is a node
  • Although they are nodes, their specific types are actually different
  • For example, tags are called element nodes, attributes are called attribute nodes, text is called text nodes, and documents are called document nodes.
  • Node types, attributes and methods are different

4. Node Properties

5. Document Node

  • Document node document, representing the entire HTML document, all nodes in a Web page are its child nodes.
  • The document object exists as a property of the window object, and we can use it directly without getting it.
  • This object allows us to find node objects throughout document access and create various node objects from it.

6. Element Node

  • Each tag in HTML is an element node, which is also one of our most common nodes
  • The browser converts all the tags on the page into an element node, which we can get by document
  • For example:
    • document.getElementById()
    • Get an element node object based on the id attribute value

7. Text Node

  • Text nodes represent text content other than HTML tags, and any non-HTML text is a text node
  • It includes plain text content with literal explanations
  • Text nodes generally exist as children of element nodes
  • When getting a text node, you usually get the element node first, then the text node through the element node
  • For example:
    • Element Node.firstChild
    • Gets the first child of an element node, typically a text node

8. Attribute Node

  • Represents one of the attributes in the tag, and it is important to note that the attribute node is not a child of the element node, but a part of the element node
  • The specified attribute node can be obtained from the element node
  • For example:
    • Element node.getAttributeNode("attribute name");
    • Note that we generally do not use attribute nodes

9. Events

  • Events, specific moments of interaction that occur in a timely document or browser window
  • The interaction between JavaScript and HTML is achieved through events
  • For web applications, there are several typical events: clicking on an element, moving the mouse over an element, pressing a key on a keyboard, and so on.

10. Get Element Nodes

  • Called through a document object
  • getElementById() Obtains an element node object based on id Book Happiness
  • getElementsByTagName() Gets a set of element node objects based on the label name
  • getElementsByName() Gets a set of element node objects based on the name attribute

11. Get child nodes of element nodes

  • Called through a specific element node
  • getElementsByTagName() returns the specified tag name descendant node of the current node
  • childNodes represents the first child node of the current node
  • lastChild represents the last child of the current node
  • fastChild represents the last child of the current node

12. Get parent and sibling nodes

  • parentNode represents the parent of the current node
  • previousSibling represents the next sibling node of the current node
  • nextSibling represents the next sibling node of the current node

13. Attributes of element nodes

  • Get element object. Attribute name
element.value
element.id
element.className
  • Set element object. Property name = new value
element.value="hello"
element.id="id001"
element.className="newClass"

14. Other attributes

  • nodeValue
    Text nodes can get and set the content of text nodes through the nodeValue property

  • innerHTML
    Element nodes can use this property to get and set HTML code inside Tags

15. demo implementation

demo implementation
demo implements several of the above scenarios

	<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>Untitled Document</title>
		<link rel="stylesheet" type="text/css" href="style/css.css" />
		<script type="text/javascript">
		
			/*
			 * Defines a function specifically designed to bind a click response function to a specified element
			 * 	Parameters:
			 * 		idStr The id property value of the object to bind the click response function
			 * 		fun A callback function for events that will be triggered when an element is clicked
			 */
			function myClick(idStr , fun){
				var btn = document.getElementById(idStr);
				btn.onclick = fun;
			}
		
			window.onload = function(){
				
				//Bind a click response function to a button with id btn01
				var btn01 = document.getElementById("btn01");
				btn01.onclick = function(){
					//Find #bj Node
					var bj = document.getElementById("bj");
					//Print bj
					//innerHTML uses this property to get html code inside an element
					alert(bj.innerHTML);
				};
				
				
				//Bind a click response function to a button with id btn02
				var btn02 = document.getElementById("btn02");
				btn02.onclick = function(){
					//Find all li nodes
					//getElementsByTagName() can get a set of element node objects based on the label name
					//This method will return us a class array object, all elements queried will be encapsulated in the object
					//Even if only one element is queried, it is encapsulated in an array and returned
					var lis = document.getElementsByTagName("li");
					
					//Print lis
					//alert(lis.length);
					
					//Variable lis
					for(var i=0 ; i<lis.length ; i++){
						alert(lis[i].innerHTML);
					}
				};
				
				
				//Bind a click response function to a button with id btn03
				var btn03 = document.getElementById("btn03");
				btn03.onclick = function(){
					//Find all nodes with name=gender
					var inputs = document.getElementsByName("gender");
					
					//alert(inputs.length);
					
					for(var i=0 ; i<inputs.length ; i++){
						/*
						 * innerHTML For getting HTML code inside an element
						 * 	This property does not make sense for self-closing Tags
						 */
						//alert(inputs[i].innerHTML);
						/*
						 * If you need to read element node properties,
						 * 	Use elements directly. Attribute names
						 * 		Example: element.id element.name element.value
						 * 		Note: The class attribute does not work this way.
						 * 			Element.className is required to read class attributes
						 */
						alert(inputs[i].className);
					}
				};
				
				//Bind a click response function to a button with id btn04
				var btn04 = document.getElementById("btn04");
				btn04.onclick = function(){
					
					//Gets the element with id city
					var city = document.getElementById("city");
					
					//Find all li nodes under #city
					var lis = city.getElementsByTagName("li");
					
					for(var i=0 ; i<lis.length ; i++){
						alert(lis[i].innerHTML);
					}
					
				};
				
				//Bind a click response function to a button with id btn05
				var btn05 = document.getElementById("btn05");
				btn05.onclick = function(){
					//Get node with id city
					var city = document.getElementById("city");
					//Return all child nodes of #city
					/*
					 * childNodes Property gets all the nodes including the text node
					 * Depending on the margin between the DOM tags, the text node will also be considered
					 * Note: Blank text is not used as a child node in browsers like IE8 and below.
					 * 	So this property returns four child elements in IE8 and nine in other browsers
					 */
					var cns = city.childNodes;
					
					//alert(cns.length);
					
					/*for(var i=0 ; i<cns.length ; i++){
						alert(cns[i]);
					}*/
					
					/*
					 * children Property can get all the child elements of the current element
					 */
					var cns2 = city.children;
					alert(cns2.length);
				};
				
				//Bind a click response function to a button with id btn06
				var btn06 = document.getElementById("btn06");
				btn06.onclick = function(){
					//Get the element with id phone
					var phone = document.getElementById("phone");
					//Return the first child node of #phone
					//phone.childNodes[0];
					//First Child gets the first child node of the current element (including a blank text node)
					var fir = phone.firstChild;
					
					//firstElementChild gets the first child element of the current element
					/*
					 * firstElementChild Browsers below IE8 are not supported.
					 * 	Try not to use them if they need to be compatible
					 */
					//fir = phone.firstElementChild;
					
					alert(fir);
				};
				
				//Bind a click response function to a button with id btn07
				myClick("btn07",function(){
					
					//Get node with id bj
					var bj = document.getElementById("bj");
					
					//Return the parent node of #bj
					var pn = bj.parentNode;
					
					alert(pn.innerHTML);
					
					/*
					 * innerText
					 * 	- This property gets the text content inside the element
					 * 	- It is similar to innerHTML except that it automatically removes html
					 */
					//alert(pn.innerText);
					
					
				});
				
				
				//Bind a click response function to a button with id btn08
				myClick("btn08",function(){
					
					//Get the element with id android
					var and = document.getElementById("android");
					
					//Return to the previous sibling node of #android (which may also get blank text)
					var ps = and.previousSibling;
					
					//previousElementSibling takes the previous sibling element, which is not supported by IE8 or below
					//var pe = and.previousElementSibling;
					
					alert(ps);
					
				});
				
				//Read the value property value of #username
				myClick("btn09",function(){
					//Gets the element with id username
					var um = document.getElementById("username");
					//Read value attribute value of um
					//The value property value of the text box is what the text box fills in
					alert(um.value);
				});
				
				
				//Set the value property value of #username
				myClick("btn10",function(){
					//Gets the element with id username
					var um = document.getElementById("username");
					
					um.value = "It's a nice day today~~~";
				});
				
				
				//Returns the text value of #bj
				myClick("btn11",function(){
					
					//Get the element with id bj
					var bj = document.getElementById("bj");
					
					//alert(bj.innerHTML);
					//alert(bj.innerText);
					
					//Get the text node in bj
					/*var fc = bj.firstChild;
					alert(fc.nodeValue);*/
					
					alert(bj.firstChild.nodeValue);
					
					
				});
				
			};
			
		
		</script>
	</head>
	<body>
		<div id="total">
			<div class="inner">
				<p>
					Which city do you like best?
				</p>

				<ul id="city">
					<li id="bj">Beijing</li>
					<li>Shanghai</li>
					<li>Tokyo</li>
					<li>Seoul</li>
				</ul>

				<br>
				<br>

				<p>
					Which single-player game do you like?
				</p>

				<ul id="game">
					<li id="rl">Red Police</li>
					<li>Fact</li>
					<li>The ultimate flying car</li>
					<li>World of Warcraft</li>
				</ul>

				<br />
				<br />

				<p>
					The operating system of your mobile phone is?
				</p>

				<ul id="phone"><li>IOS</li> <li id="android">Android</li><li>Windows Phone</li></ul>
			</div>

			<div class="inner">
				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>
		</div>
		<div id="btnList">
			<div><button id="btn01">lookup#bj node </button> </div>
			<div><button id="btn02">Find All li node</button></div>
			<div><button id="btn03">lookup name=gender All Nodes</button></div>
			<div><button id="btn04">lookup#All li nodes under city </button> </div>
			<div><button id="btn05">Return#All child nodes of city </button></div>
			<div><button id="btn06">Return#phone's first child node </button> </div>
			<div><button id="btn07">Return#bj's parent node </button> </div>
			<div><button id="btn08">Return#android's previous sibling node </button> </div>
			<div><button id="btn09">Return#Value property value of username </button> </div>
			<div><button id="btn10">Set up#Value property value of username </button> </div>
			<div><button id="btn11">Return#Text value of bj </button> </div>
		</div>
	</body>
</html>

				

15. Picture Switching Implementation

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    * {
        padding: 0;
        margin: 0;
    }

    #temp {
        width: 500px;
        margin: 50px auto;
        padding: 10px;
        background-color: greenyellow;
        /*Set text centering*/
        text-align: center;
    }
</style>

<body>
    <div id="temp">
        <p id="side"></p>
        <img src="./img/1.jpg" alt="">
        <button id="prev">Previous</button>
        <button id="next">Next</button>
    </div>
    <script>
        /**
         * Requirements: User clicks the previous button to switch to the previous picture, clicks the next button to switch to the next picture, and the picture shows the current number of pages
         */
        //  Button to get id prev
        var prev = document.getElementById("prev");
        // Button to get id next
        var next = document.getElementById("next");

        // Store all picture paths
        var imgLocs = ["./img/1.jpg", "./img/2.jpg", "./img/3.jpg", "./img/4.jpg", "./img/5.jpg",]

        // page
        var index = 0;

        // Get img object
        var img = document.getElementsByTagName("img")[0];

        // Get page number display information
        var side = document.getElementById("side");
        side.innerHTML = "Altogether" + imgLocs.length + "page," + "Current" + (index + 1) + "page"
        prev.onclick = function () {
            index--;
            if (index < 0) {
                index = imgLocs.length - 1;
            }
            img.src = imgLocs[index];
            side.innerHTML = "Altogether" + imgLocs.length + "page," + "Current" + (index + 1) + "page"
        }
        next.onclick = function () {
            index++;
            if (index > imgLocs.length - 1) {
                index = 0
            }
            img.src = imgLocs[index];
            side.innerHTML = "Altogether" + imgLocs.length + "page," + "Current" + (index + 1) + "page"
        }
    </script>
</body>

</html>

Design sketch

16. Query using css selector

querySelector()
querySelectorAll()

  • Both methods are called with a document object. Both methods use the same method, passing a selector string as a parameter, and the method automatically searches the web page for elements based on the selector string
  • The difference is that querySelector() only returns the first element found, while querySelectorAll() returns all elements that meet the criteria
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="box2"></div>
    <div class="box1">
        I'm the first box1
        <div>I am box1 In div</div>
    </div>
    <div class="box1">
        <div>I am box1 In div</div>
    </div>
    <div class="box1">
        <div>I am box1 In div</div>
    </div>
    <div class="box1">
        <div>I am box1 In div</div>
    </div>

    <div></div>
    <script>
        // Get the body tag
        // var body = document.getElementsByTagName("body")[0];

        // There is an attribute body in the document that holds a reference to the body
        var body = document.body;

        // document.documentElement holds html and Tags
        var html = document.documentElement;

        // document.all represents all elements on the page
        var all = document.all;

        console.log(all.length);

        for (var i = 0; i < all.length; i++) {
            console.log(all[i])
        }

        all = document.getElementsByTagName("*");
        console.log(all.length);

        /**
         * Query a set of element node objects based on their class attribute values
         * getElementsByClassName()You can get a set of element node objects based on class attribute values
         * However, this method does not support IE8 and browsers below
         */
        var box1 = document.getElementsByClassName("box1");
        console.log(box1.length)

        // Get all div s on the page
        var divs = document.getElementsByTagName("div");
        console.log(divs)

        // Get all div s with class box1
        // .box1 div
        /**
         * document.querySelector()
         * A string that requires a selector as a parameter and can be queried against a css selector
         * Element node object although IE8 does not have getElmentsByClassName()
         * You can use querySelector() instead
         * This method always returns the only element. If there are more than one element that meets the criteria, then
         * It only returns the first
         */
        var digv = document.querySelector(".box1 div")
        console.log(digv)

        var box11 = document.querySelector(".box1")
        console.log(box11)

        console.log(box11.innerHTML)
        console.log(digv.innerHTML)

        /**
         * document.querySelectorAll()
         * This method is similar to the querySelector() method except that it encapsulates qualifying elements in one
         * Return from an array It returns an array even if only one meets the criteria
         */
        var abc = document.querySelectorAll(".box1");
        var bcd = document.querySelectorAll("#box2");
        console.log(abc)
        console.log(bcd)

    </script>
</body>

</html>

16. Modification of nodes

  • Modifications here refer primarily to modifications to element nodes
  • Create Node
    • Document.createElement (label name)
  • Delete Node
    • Parent node.removeChild (child node)
  • Replace Node
    • Parent node.replaceChild (new node, old node)
  • Insert Node
    • Parent node.appendChild (child node)
    • Parent node.insertBefore (new node, old node)
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="total">
        <div class="inner">
            <p>
                Which city do you like best?
            </p>

            <ul id="city">
                <li id="bj">Beijing</li>
                <li>Shanghai</li>
                <li>Tokyo</li>
                <li>Seoul</li>
            </ul>

        </div>
    </div>
    <div id="btnList">
        <div><button id="btn01">Create a"Guangzhou"node,add to#Under city </button> </div>
        <div><button id="btn02">take"Guangzhou"Node inserts into#bj front </button></div>
        <div><button id="btn03">Use"Guangzhou"Node Replacement#bj node </button> </div>
        <div><button id="btn04">delete#bj node </button> </div>
        <div><button id="btn05">read#HTML code within city </button></div>
        <div><button id="btn06">Set up#HTML code within bj </button></div>
        <div><button id="btn07">Create a"Guangzhou"node,add to#Under city </button> </div>
    </div>
    <script>
        // 1. Create a "Guangzhou" node and add it to #city
        var btn01 = document.getElementById("btn01");
        btn01.onclick = function () {
            // Create Guangzhou Node <li>Guangzhou </li>
            // Create li element node
            /**
             * document.createElement()
             * You can create an element node object
             * It requires a label name as a parameter and will create element node objects based on the label name
             * And returns the object with the creation number as a return value
             */
            var li = document.createElement("li");

            // Create Guangzhou Text Node
            var gzText = document.createTextNode("Guangzhou");

            // Set gzText to a child node of li
            /**
             * appendChild()
             * Add a new child node to a parent node
             * Usage: parent node. appendChild (child node)
             */
            li.appendChild(gzText);

            // Get node with id city
            var city = document.getElementById("city");
            // Add Guangzhou Node to city
            city.appendChild(li);
        }

        // 2. Insert "Guangzhou" node in front of #bj
        var btn02 = document.getElementById("btn02");
        btn02.onclick = function () {
            // Create a Guangzhou
            var li = document.createElement("li");
            var gzText = document.createTextNode("Guangzhou");
            // Append Guangzhou Text Node
            li.appendChild(gzText);

            // Get node with id bj
            var bj = document.getElementById("bj");
            // Get city
            var city = document.getElementById("city");

            /**
             * insertBefore()
             * New child nodes can be inserted before specified child nodes
             * Syntax: parent node. insertBefore (new node, old node)
             */
            city.insertBefore(li, bj);

        }

        // 3. Replace #bj node with Guangzhou node
        var btn03 = document.getElementById("btn03");
        btn03.onclick = function () {
            var li = document.createElement("li");
            var gzText = document.createTextNode("Guangzhou");
            li.appendChild(gzText)

            // Get city Node
            /**
             * replaceChild()
             * Existing child nodes can be replaced with specified child nodes
             * Syntax: parent node. replaceChild (new node, old node)
             */
            var city = document.getElementById("city");
            var bj = document.getElementById("bj");
            city.replaceChild(li, bj);
        }

        // 4. Delete #bj Node
        var btn04 = document.getElementById("btn04");
        btn04.onclick = function () {
            var bj = document.getElementById("bj")
            var city = document.getElementById("city")
            /**
             * removeChild()
             * You can delete a child node
             * Parent node.removeChild (child node)
             * Child Node.parentNode.removeChild (Child Node)
             */
            // Delete from parent node
            // city.removeChild(bj);
            // Delete by child node when there is no parent node
            // bj.parentNode.removeChild(bj);
        }

        // 5. Read HTML code in #city
        var btn05 = document.getElementById("btn05");
        btn05.onclick = function () {
            //Get city
            var city = document.getElementById("city");
            alert(city.innerHTML);
        }

        // 6. Set up html code within #bj
        var btn06 = document.getElementById("btn06");
        btn06.onclick = function () {
            var bj = document.getElementById("bj");
            bj.innerHTML = "The mighty river flows eastward"
        }

        // 7. Create a "Guangzhou" node and add it to #city
        var btn07 = document.getElementById("btn07");
        btn07.onclick=function(){
            var li = document.createElement("li");
            var gzText=document.createTextNode("Guangzhou");
            li.appendChild(gzText);

            var city = document.getElementById("city");
            city.appendChild(li);
        }
    </script>
</body>

</html>

17. Add Delete Practice

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Add delete record exercise</title>
<link rel="stylesheet" type="text/css" href="ex_2_style/css.css" />
<script type="text/javascript">

	function removeTr(){
		var trNode = this.parentNode.parentNode;
		var tds = trNode.getElementsByTagName("td");
		var nameStr = tds[0].firstChild.nodeValue;
		var flag = confirm("Really want to delete" + nameStr + "Information?");
		if(flag){
			trNode.parentNode.removeChild(trNode);
		}
		// Cancel default behavior
		return false;
	}

	window.onload = function(){
		//Goal 1: Click Delete to delete records
		var aEles = document.getElementsByTagName("a");
		for(var i = 0;i < aEles.length;i++){
			aEles[i].onclick = removeTr;
		}
		
		//Goal 2: Click Submit to add records
		var subBtn = document.getElementById("addEmpButton");
		subBtn.onclick = function(){
			var nameText = trim(document.getElementById("empName").value);
			var emailText = trim(document.getElementById("email").value);
			var salaryText = trim(document.getElementById("salary").value);
			
			document.getElementById("empName").value = nameText;
			document.getElementById("email").value = emailText;
			document.getElementById("salary").value = salaryText;
			
			if(nameText == "" || emailText == "" || salaryText == ""){
				alert("Your input is incomplete");
				return ;
			}
			
			//Assembly Node
			var nameTd = document.createElement("td");
			nameTd.appendChild(document.createTextNode(nameText));
			var emailTd = document.createElement("td");
			emailTd.appendChild(document.createTextNode(emailText));
			var salaryTd = document.createElement("td");
			salaryTd.appendChild(document.createTextNode(salaryText));
			var aTd = document.createElement("td");
			var aNewEle = document.createElement("a");
			aNewEle.href = "deleteEmp?id=XXX";
			aNewEle.appendChild(document.createTextNode("Delete"));
			aNewEle.onclick = removeTr;
			aTd.appendChild(aNewEle);
			
			var trNode = document.createElement("tr");
			trNode.appendChild(nameTd);
			trNode.appendChild(emailTd);
			trNode.appendChild(salaryTd);
			trNode.appendChild(aTd);
			
			var empTable = document.getElementById("employeeTable");
			empTable.appendChild(trNode);
		}
		
		function trim(str){
			var reg = /^\s*|\s*$/g;
			return str.replace(reg,"");
		}
		
	}
</script>
</head>
<body>

	<table id="employeeTable">
		<tr>
			<th>Name</th>
			<th>Email</th>
			<th>Salary</th>
			<th>&nbsp;</th>
		</tr>
		<tr>
			<td>Tom</td>
			<td>tom@tom.com</td>
			<td>5000</td>
			<td><a href="deleteEmp?id=001">Delete</a></td>
		</tr>
		<tr>
			<td>Jerry</td>
			<td>jerry@sohu.com</td>
			<td>8000</td>
			<td><a href="deleteEmp?id=002">Delete</a></td>
		</tr>
		<tr>
			<td>Bob</td>
			<td>bob@tom.com</td>
			<td>10000</td>
			<td><a href="deleteEmp?id=003">Delete</a></td>
		</tr>
	</table>

	<div id="formDiv">
	
		<h4>Add new employees</h4>

		<table>
			<tr>
				<td class="word">name: </td>
				<td class="inp">
					<input type="text" name="empName" id="empName" />
				</td>
			</tr>
			<tr>
				<td class="word">email: </td>
				<td class="inp">
					<input type="text" name="email" id="email" />
				</td>
			</tr>
			<tr>
				<td class="word">salary: </td>
				<td class="inp">
					<input type="text" name="salary" id="salary" />
				</td>
			</tr>
			<tr>
				<td colspan="2" align="center">
					<button id="addEmpButton" value="abc">
						Submit
					</button>
				</td>
			</tr>
		</table>

	</div>

</body>
</html>

Design sketch

18. Operating css with dom

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			
			#box1{
				width: 100px;
				height: 100px;
				background-color: red;
			}
			
		</style>
		
		<script type="text/javascript">
			
			window.onload = function(){
				
				/*
				 * After clicking the button, change the size of box 1
				 */
				//Get box1
				var box1 = document.getElementById("box1");
				//Bind Click Response Functions to Buttons
				var btn01 = document.getElementById("btn01");
				btn01.onclick = function(){
					
					//Modify the width of box 1
					/*
					 * Modify the style of an element through JS:
					 * 	Syntax: element.style.style name=style value
					 * 
					 * Note: If the style name of the CSS contains -,
					 * 		This name is illegal in JS, such as background-color
					 * 		This style name needs to be changed to the hump nomenclature.
					 * 		Remove -, and then capitalize the letter after -.
					 * 
					 * The styles we set through the style property are inline styles.
					 * 	Inline styles have a higher priority, so styles modified through JS tend to appear immediately
					 * 
					 * But if it's written in a style!important, then the style will have the highest priority.
					 * 	The style cannot be overwritten even through JS, which will invalidate the JS modified style
					 * 	So try not to add styles!important
					 * 
					 * 
					 * 
					 */
					box1.style.width = "300px";
					box1.style.height = "300px";
					box1.style.backgroundColor = "yellow";
					
				};
				
				
				//Read the style of the element after clicking Button 2
				var btn02 = document.getElementById("btn02");
				btn02.onclick = function(){
					//Read the style of box 1
					/*
					 * 	Syntax: element.style.style name
					 * 
					 * All styles set and read through the style property are inline
					 * 	Unable to read styles from stylesheet
					 */
					//alert(box1.style.height);
					alert(box1.style.width);
				};
			};
			
			
		</script>
	</head>
	<body>
		
		<button id="btn01">Give me a click</button>
		<button id="btn02">Give me a click 2</button>
		
		<br /><br />
		
		<div id="box1"></div>
		
	</body>
</html>

19. Styles for reading elements

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			
			#box1{
				width: 100px;
				height: 100px;
				background-color: yellow;
			}
			
		</style>
		
		<script type="text/javascript">
			
			window.onload = function(){
				
				//Read the style of box 1 after clicking the button
				var box1 = document.getElementById("box1");
				var btn01 = document.getElementById("btn01");
				btn01.onclick = function(){
					//Read the width of box 1
					//alert(box1.style.width);
					
					/*
					 * Gets the current display style of the element
					 * 	Syntax: element. currentStyle. style name
					 * It can be used to read the style that the current element is displaying
					 * 	Gets the default value of the current element if it is not styled
					 * 
					 * currentStyle Only IE browsers support it, not others
					 */
					
					//alert(box1.currentStyle.width);
					//box1.currentStyle.width = "200px";
					//alert(box1.currentStyle.backgroundColor);
					
					/*
					 * Can be used in other browsers
					 * 		getComputedStyle()This method gets the current style of the element
					 * 		This method is a window method and can be used directly
					 * Two parameters are required
					 * 		First: to get the elements of the style
					 * 		Second: you can pass a pseudo element, typically null
					 * 
					 * This method returns an object that encapsulates the corresponding style of the current element
					 * 	Styles can be read by object. style name
					 * 	If the style you get is not set, you get the real value instead of the default value
					 * 	For example, if you do not set width, it will not get auto, but a length
					 * 
					 * However, this method does not support browsers with IE8 or below
					 * 
					 * Styles read through currentStyle and getComputedStyle() are read-only.
					 * 	Cannot modify, if you want to modify it you must pass the style attribute
					 */
					//var obj = getComputedStyle(box1,null);
					
					/*alert(getComputedStyle(box1,null).width);*/
					//Normal browser style
					//alert(getComputedStyle(box1,null).backgroundColor);
					
					//Ways of IE8
					//alert(box1.currentStyle.backgroundColor);
					
					//alert(getStyle(box1,"width"));
					
					var w = getStyle(box1,"width");
					alert(w);
					
					
				};
				
			};
			
			/*
			 * Define a function to get the current style of the specified element
			 * Parameters:
			 * 		obj Elements to get styles
			 * 		name Style name to get
			 */
			
			function getStyle(obj , name){
				
				if(window.getComputedStyle){
					//Normal browser style, with getComputedStyle() method
					return getComputedStyle(obj , null)[name];
				}else{
					//IE8 mode, no getComputedStyle() method
					return obj.currentStyle[name];
				}
				
				//return window.getComputedStyle?getComputedStyle(obj , null)[name]:obj.currentStyle[name];
				
			}
			
			
		</script>
	</head>
	<body>
		<button id="btn01">Give me a click</button>
		<br /><br />
		<div id="box1" ></div>
	</body>
</html>

20. Other attribute operations

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
        #box1 {
            width: 100px;
            height: 100px;
            background-color: red;
            padding: 10px;
            border: 10px solid yellow;
        }


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

        #box4 {
            width: 200px;
            height: 300px;
            background-color: #bfa;
            overflow: auto;
        }

        #box5 {
            width: 450px;
            height: 600px;
            background-color: yellow;
        }
    </style>
    <script type="text/javascript">

        window.onload = function () {
            var box1 = document.getElementById("box1");
            var btn01 = document.getElementById("btn01");
            var box4 = document.getElementById("box4");

            btn01.onclick = function () {
                /*
                 * clientWidth
                 * clientHeight
                 * 	- These two attributes get the visible width and height of the element
                 * 	- These attributes are all px-free, return is a number, and can be calculated directly
                 * 	- Gets the width and height of the element, including the content area and the interior margin
                 *  - These properties are read-only and cannot be modified
                 */
                //alert(box1.clientWidth);
                //alert(box1.clientHeight);
                //box1.clientHeight = 300;

                /*
                 * offsetWidth
                 * offsetHeight
                 * 	- Gets the entire width and height of the element, including the content area, inner margin, and border
                 */
                //alert(box1.offsetWidth);

                /*
                 * offsetParent
                 * 	- The positioned parent element that can be used to get the current element
                 *  - Gets the closest ancestor element to the current element with positioning turned on
                 * 		Return body if all ancestor elements are not positioned on
                 */
                var op = box1.offsetParent;

                //alert(op.id);

                /*
                 * offsetLeft
                 * 	- The horizontal offset of the current element from its positioned parent
                 * offsetTop
                 * 	- The vertical offset of the current element from its positioned parent
                 */

                //alert(box1.offsetLeft);

                /*
                 * scrollWidth
                 * scrollHeight
                 * 	- You can get the width and height of the entire scrolling area of an element
                 */
                //alert(box4.clientHeight);
                //alert(box4.scrollWidth);

                /*
                 * scrollLeft
                 * 	- You can get the distance the horizontal scrollbar scrolls
                 * scrollTop
                 * 	- You can get the distance a vertical scrollbar scrolls
                 */
                //alert(box4.scrollLeft);
                //alert(box4.scrollTop);

                //alert(box4.clientHeight); // 283

                //When scrollHeight - scrollTop == clientHeight is satisfied
                //Vertical scrollbar scrolls to the end

                //When scrollWidth is satisfied - scrollLeft == clientWidth
                //Explains that the horizontal scrollbar scrolls to the bottom
                //alert(box4.scrollHeight - box4.scrollTop); // 600



            };

        };


    </script>
</head>

<body id="body">
    <button id="btn01">Give me a click</button>
    <br /><br />

    <div id="box4">
        <div id="box5"></div>
    </div>



    <br /><br />

    <div id="box3">
        <div id="box2" style="position: relative;">
            <div id="box1"></div>
        </div>
    </div>


</body>

</html>

Tags: Javascript Front-end html5 html

Posted on Mon, 06 Sep 2021 12:56:23 -0400 by PHP Monkeh