What is DOM? DOM is a set of API interfaces based on browser programming (in this tutorial, it can be said to be DHTML programming). W3C has some subtle differences in each browser. Among them, Mozilla's browser is the most similar to the standard. Simple Javascript must combine DOM to perform DHTML programming, and can produce beautiful effects and be applied to WEB. This is almost the same as other languages, just as C/C++ requires library support. Otherwise, it is simply a grammatical research. What we are most concerned about is that DOM connects web pages with scripts and other programming languages. DOM belongs to the browser, not the core content specified in the JavaScript language specification.
Find elements
1. Search directly
| Method name | describe |
| getElementById(id) (document) | Get elements in the document with a specified unique ID attribute value |
| getElementsByTagName_r(name) | Returns an array of child elements with specified tagname in the current element |
| document.getElementsByClassName | Get the tag collection based on attributes |
| getAttribute(name) | Returns the attribute value of the element, the attribute is specified by name |
1>document.getElementById('id')
<body> <div id="zhang"> Not handsome</div> <script type="text/javascript"> var i = document.getElementById('zhang'); //Find the specified id i.innerText = 'very handsome'; //innerText modify the specified string</script></body>Display effect, when we open IE, it will be modified to be very handsome.
2>getElementsByTagName_r(name)
<body> <div name="zhang"> Not handsome</div> <script type="text/javascript"> var i = document.getElementByTagNmae('zhang'); //Find the specified name name i.innerText = 'very handsome'; //innerText modify the specified string</script></body>The same display effect
3>document.getElementsByClassName
<body> <div> Not handsome</div> <script type="text/javascript"> var i = document.getElementClassName('zhang'); //Find the specified class name i.innerText = 'very handsome'; //innerText modify the specified string</script></body>2. Indirect search
| Attribute name | describe |
| childNodes | Returns an array of all child elements of the current element |
| childNodes | Returns all child elements of the current element |
| firstChild | Returns the first lower child element of the current element |
| lastChild | Returns the last child element of the current element |
| nextSibling | Returns the element immediately following the current element |
| PreviousSibling | Returns the element immediately preceding the current element |
| parentElement | Returns its parent node label element |
| children | Return all its subtitles |
| firstElementChild | Returns the first subtitle element |
| lastElementChild | Returns the last subtag element |
| nextElementtSibling | Return下一个兄弟标签元素 |
| PreviousElementSibling | Return to the previous sibling tag element |
With W3C DOM, you can write simple cross-browser scripts, taking full advantage of the power and flexibility of XML to use XML as a communication medium between the browser and the server.
Operation elements
1. W3C DOM properties and methods used to create content dynamically
| Properties/Methods | describe |
| document.createElement_x(tagName) | The createElement_x method on the document object can create elements specified by tagName. If the string div is used as the method parameter, a div element will be generated |
| document.createTextNode(text) | The createTextNode method of the document object will create a node containing static text. |
| <element>.appendChild(childNode) | The appendChild method adds the specified node to the current element's child node list (as a new child node). |
| <element>.setAttribute(name, value) | These methods respectively obtain and set the value of the name attribute in the element |
| <element>.insertBefore(newNode, targetNode) | Insert node newNode as the child node of the current element in front of the targetNode element |
| <element>.removeAttribute(name) | This method deletes the attribute name from the element |
| <element>.removeChild(childNode) | This method removes child element childNode from the element |
| <element>.replaceChild(newNode, oldNode) | This method replaces the node oldNode with the node newNode |
| <element>.hasChildnodes() | This method returns a Boolean value indicating whether the element has child elements |
2. Tag content
innerText Get the tag text content innerHTML Get the HTML content value Get the value, that is, the value of the form submitted form
That is, the following is the following:
<div>1111</div><div>2222</div><input type="text" value="Zhang Yanlin"><script> document.getElementsByClassName("zhang").innertext = 123; // Get the tag with the class name zhang and change the content to 123 document.getElementsByClassName("yan").innerHTML = 456; // Get the tag with the class name yan and change the content to 456 document.getElementsByClassName("lin").value = "Zhang Yanlin is handsome"; // Get the tag with the class name lin and change the content to Zhang Yanlin is handsome</script>3. Attributes
attributes // Get all tag attributes setAttribute(key,value) // Set tag attribute getAttribute(key) // Get the specified tag attribute
Through custom properties, you can make a case of selecting all, unselecting, and deselecting. The code is as follows:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body><div> <input type="button" value="Select all" onclick="Checkall();"> <input type="button" value="Cancel" onclick="Cancleall();"> <input type="button" value="undelect" onclick="recvall();"></div><div id = "i1"> <ul> <li><input type="checkbox" value="1">Basketball</li> <li><input type="checkbox" value="2">Football</li> <li><input type="checkbox" value="3">Volleyball</li> </ul></div><script> function Checkall() { var b = document.getElementsByClassName("c1"); for (var i = 0 ;i < b.length;i++){ var check = b[i]; check.checked = true } } function Cancleall() { var b = document.getElementsByClassName("c1"); for (var i = 0 ;i < var i = 0 ;i < b.length;i++){ var check = b[i]; check.checked = false } } function recvall() { var b = document.getElementsByClassName("c1"); for (var i = 0 ;i < b.length;i++){ var check = b[i]; if (check.checked){ check.checked = false }else { check.checked = true } } }</script></body></html>Select all, reverse, cancel casesNote: onclick is a click event, which will be mentioned later
4. Class operation
className // Get all class names classList.remove(cls) // Delete the specified class classList.add(cls) // Add class
This thing is very useful. For example, in JD.com, when our mouse is placed on all the products, many products appear below. The products are hidden and only appear after the triggering event is to define a css hidden attribute. After the mouse is placed on, the CSS hidden attribute is removed; the mouse is removed and the hidden attribute is added.
<!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8"> <title>Hide</title> <style> .hide{ display: none; } </style></head><body><span onmouseover="mouOver();">Put something out of it, but it disappears without putting it</span><div id = "zhangyanlin" style="font-size: 60px">Zhang Yanlin is so handsome</div><script> function mouOver() { document.getElementById("zhangyanlin").classList.remove("hide"); } function mouOut() { document.getElementById("zhangyanlin").classList.add("hide"); }</script></body></html> Let's wake up the brain with a case5. Tag operation
We can create tags through dom and add them to the specified location. Here are two methods to operate tags
// Method one var zhang = "<input type='text' />";xxx.insertAdjacentHTML("beforeEnd",zhang);xxx.insertAdjacentElement('afterBegin',document.createElement('a')) //Note: the first parameter can only be 'beforeBegin', 'afterBegin', 'beforeEnd', 'afterEnd' // Method two var tag = document.createElement('div')xxx.appendChild(tag) //Add a div element xxx.insertBefore(tag,xxx[1]) //Insert to the specified position, you can use the index <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body> <div> <div> <input type="text" /> <input type="button" value="add" onclick="AddElement(this);" /> </div> <div style="position: relative;"> <ul id="commentList"> <li>alex</li> <li>eric</li> </ul> </div> </div> <script> function AddElement(ths) { // Get the input value var val = ths.previousElementSibling.value; ths.previousElementSibling.value = ""; var commentList = document.getElementById('commentList'); //The first form, string method//var str = "<li>" + val + "</li>"; // 'beforeBegin', 'afterBegin', 'beforeEnd', 'afterEnd' // beforeEnd internal last// beforeBegin external upper//afterBegin internal close-fitting//afterEnd External wall pasting //commentList.insertAdjacentHTML("beforEnd",str); //The second method is the element method var tag = document.createElement('li'); tag.innerText = val; var temp = document.createElement('a'); temp.innerText = 'Baidu'; temp.href = "http://etiantian.org"; tag.appendChild(temp); // commentList.appendChild(tag); commentList.insertBefore(tag,commentList.children[1]); } </script></body></html>Add tag operation case6. Style operation
<body><div id = i1>Zhang Yanlin is handsome</div><script>var obj = document.getElementById('i1');obj.style.fontSize = "32px";obj.style.backgroundColor = "red";</script></body>The effects are as follows:
Let’s take a case. Just looking at the knowledge points is boring. We often see the darker font in the input box, which prompts you to enter something. When you click in, it disappears. It’s a magical operation. It is achieved through the dom. Just read the code without saying much nonsense.
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <style> .bb{ color: #9a9a9a; } .aa{ color: black; } </style></head><body> <input value="Please enter content" onfocus="inpAtu(this);" onblur="onBtu(this);"> <script> function inpAtu(ths) { ths.className = "aa"; var text = ths.value; if (text == "Please enter content"){ ths.value = ""; } } function onBtu(ths) { var text = ths.value; if (text == "Please enter content" || text.trim().length == 0){ ths.className = "bb"; ths.value = "Please enter content"; } } </script></body></html>input input box prompt7. Position operation
Total document height document.documentElement.offsetHeight Current document occupies screen height document.documentElement.clientHeight Self-height tag.offsetHeight Distance to the superior positioning height tag.offsetTop Parent positioning tag tag.offsetParent scrolling height tag.scrollTop
Did you think that there is a return to the top at the lower right corner of the web page and then return to the top at a slightest point? Yes, it is to calculate these heights; and when you pull down the mouse, the corresponding style of the menu bar on the left will change.
<!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8"> <title></title></head><style> body{ margin: 0px; } img { border: 0; } ul{ padding: 0; margin: 0; list-style: none; } h1{ padding: 0; margin: 0; } .clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; } .wrap{ width: 980px; margin: 0 auto; } .pg-header{ background-color: #303a40; -webkit-box-shadow: 0 2px 5px rgba(0,0,0,.2); -moz-box-shadow: 0 2px 5px rgba(0,0,0,.2); box-shadow: 0 2px 5px rgba(0,0,0,.2); } .pg-header .logo{ float: left; padding:5px 10px 5px 0px; } .pg-header .logo img{ vertical-align: middle; width: 110px; height: 40px; } .pg-header .nav{ line-height: 50px; } .pg-header .nav ul li{ float: left; } .pg-header .nav ul li a{ display: block; color: #ccc; padding: 0 20px; text-decoration: none; font-size: 14px; } .pg-header .nav ul li a:hover{ color: #fff; background-color: #425a66; } .pg-body{ } .pg-body .catalog{ position: absolute; top:60px; width: 200px; background-color: #fafafa; bottom: 0px; } .pg-body .catalog.fixed{ position: fixed; top:10px; } .pg-body .catalog .catalog-item.active{ color: #fff; background-color: #425a66; } .pg-body .content{ position: absolute; top:60px; width: 700px; margin-left: 210px; background-color: #fafafa; overflow: auto; } .pg-body .content .section{ height: 500px; border: 1px solid red; }</style><body onscroll="ScrollEvent();"><div> <div> <div> <a href="#"> <img src="http://core.pc.lietou-static.com/revs/images/common/logo_7012c4a4.pn"> </a> </div> <div> <ul> <li> <a href="#">Home</a> </li> <li> <a href="#">Function 1</a> </li> <li> <a href="#">Function 2</a> </li> </ul> </div> </div> </div></div><div> <div> <div id="catalog"> <div auto-to="function1"><a>Picture 1</a></div> <div auto-to="function2"><a>Picture 2</a></div> <div auto-to="function3"><a>Picture 3</a></div> </div> <div id="content"> <div menu="function1"> <h1>Chapter 1</h1> </div> <div menu="function2"> <h1>Chapter 2</h1> </div> <div menu="function3"> <h1>Chapter 3</h1> </div> </div> </div> </script> <script> function ScrollEvent(){ var bodyScrollTop = document.body.scrollTop; if(bodyScrollTop>50){ document.getElementsByClassName('catalog')[0].classList.add('fixed'); }else{ document.getElementsByClassName('catalog')[0].classList.remove('fixed'); } var content = document.getElementById('content'); var sections = content.children; for(var i=0;i<sections.length;i++){ var current_section = sections[i]; // The absolute height of the current label from the top var scOffTop = current_section.offsetTop + 60; // The current label from the top, the relative height var offTop = scOffTop - bodyScrollTop; // The current label height var height = current_section.scrollHeight; if(offTop<0 && -offTop < height){ // The current label adds active // Other removal of active var menus = document.getElementById('catalog').children; var current_menu = menus[i]; current_menu.classList.add('active'); for(var j=0;j<menus.length;j++){ if(menus[j] == current_menu){ }else{ menus[j].classList.remove('active'); } } break; } } } } </script></body></html>Scroll menu <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <style> .pg-top{ position: fixed; background-color: #0095bb; height: 40px; width: 40px; bottom: 50px; right: 40px; color: whitesmoke; } .hide{ display: none; } </style></head><body onscroll="Func();"> <div style="height: 3000px;" id = "i1"> <h1>Zhang Yanlin</h1> </div> <div id = "i2"> <a href="javascript:void(0);" onclick="GoTop();">Return to top</a> </div><script> function Func() { var scrollTop = document.body.scrollTop; var i1 = document.getElementById("i2"); if (scrollTop>20){ i1.classList.remove("hide") }else { i1.classList.add("hide") } } function GoTop() { document.body.scrollTop = 0; }</script></body></html>Back to top8. Other operations
console.log output box alert pop-up box confirm confirm confirm box // URL and refresh location.href Get URLlocation.href = "url" Redirect location.reload() Reload // Timer setInterval Multiple timer clearInterval Clear multiple timer setTimeout Single timer clearTimeout Clear single timer
Let me tell you about the timer. Timer is more useful. For example, when we delete an email, we will find a conversation pop-up. The email has been deleted. This is a single timer. Multiple timer can be used when you have specific needs.
// Multiple timer case <input type="button" value="Interval" onclick="Interval();"><input type="button" value="StopInterval" onclick="StopInterval();"> <script> function Interval() { s1 = setInterval(function () { console.log(123) //Continuous output 123 },500); s1 = setInterval(function () { console.log(123) },500); } function StopInterval() { clearInterval(s1); //Clear one multiple timer} </script>Single timer
<div> <input type="button" value="Delete" onclick="Delete();"> <input type="button" value="Keal the current status" onclick="UnDelete();"> <div id = "status"></div> </div> <script> function Delete() { document.getElementById("status").innerText = "Deleted"; t1 = setTimeout(Clearstatus,1500); } function Clearstatus() { document.getElementById("status").innerText = ""; } function UnDelete() { clearTimeout(t1); // After clearing the timer, it will keep showing} </script>event
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body> // Normal Event<button id = "btn1" onclick="func();">Button</button> <script> var btn = document.getElementById("btn1"); function func() { alert("normal time processing") } </script> // Level 0 processing event<button id = "btn2"> Level 0 processing button</button> <script> var btn = document.getElementById("btn2"); btn.onclick = function () { alert("0-level processing button") };// btn.onclick = null; // Clear event processing, multiple events will be overwritten, leaving only the last event</script> // Level 2 processing event <button id = "btn3"> Level 2 processing button</button> <script> var btn = document.getElementById("btn3").addEventListener("click",function () { alert("second-level processing event 1") }); var btn1= document.getElementById("btn3").addEventListener("click",function () { alert("secondary processing event 2") }); //Not overwritten</script> <button id = "btn4">full compatible button</button> <script> var btn = document.getElementById("btn4"); if (btn.addEventListener){ btn.addEventListener("click",demo); }else if(btn.attachEvent){ btn.attachEvent("onclick",demo); }else { btn.onclick = demo; } function demo() { alert("integrated compatibility event handling") } </script></body></html>Event list:
| property | When does this event occur (when is triggered) |
| onabort | Image loading is interrupted |
| onblur | The element loses focus |
| onchange | The content of the area has been modified |
| onclick | The event handle called when the user clicks on an object (executing the above code example when clicking the input tag) |
| ondblclick | Event handle called when the user double-clicks an object |
| onerror | An error occurred while loading a document or image |
| onfocus | Elements gain focus |
| onkeydown | A keyboard key is pressed |
| onkeypress | A keyboard key is pressed and released |
| onkeyup | A keyboard is released |
| onload | A page or a picture is loaded |
| onmousedown | The mouse button is pressed |
| onmousemove | After the mouse moves over |
| onmouseout | Mouse is removed from an element |
| onmouseover | Move the mouse over an element |
| onmouseup | Mouse button is released |
| onreset | The reset button is clicked |
| onresize | The window or frame is resized |
| onselect | Text selected |
| onsubmit | The confirmation button is clicked |
| onunload | User exit page |
Note: A tag can bind multiple events, this tag is currently operating, and the event encapsulates the content of the current event.
Let's have a few cases, otherwise I feel like I haven't seen it after reading it
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <style> ul{ list-style: none; padding: 0; margin: 0; } ul li{ float: left; background-color: #038CAE; color: white; padding: 15px 20px; } .clearfix:after{ display: block; content: '.'; height: 0; visibility: hidden; clear: both; } .hide{ display: none; } .tab-menu{ border: 1px solid #dddddd; } .tab-menu .title{ background-color: #dddddd; } .tab-menu .title .active{ background-color: white; color: black; border-top: 2px solid red; } .tab-menu .content{ border: 1px solid #dddddd; min-height: 150px; } </style></head><body> <div> <div> <div> <ul> <li target = "h1" onclick="Show(this);">Price Trends</li> <li target = "h2" onclick="Show(this);">Market Distribution</li> <li target = "h3" onclick="Show(this);">Others</li> </ul> </div> <div id = "content"> <div con = "h1">content1</div> <div con = "h2">content2</div> <div con = "h3">content3</div> </div> </div> </div> </div> </div> </div> </div><script> function Show(ths) { var target = ths.getAttribute('target'); ths.className = 'active'; var brother = ths.parentElement.children; for (var i=0;i<brother.length;i++){ if (ths == brother[i]){ }else { brother[i].removeAttribute("class"); } } var content = document.getElementById("content").children; for (var j=0;j<content.length;j++){ var current_content = content[j]; var con = current_content.getAttribute("con"); if (con == target){ current_content.classList.remove("hide"); }else { current_content.className = "hide"; } } } }</script></body></html>Tag menu case <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body> <input type="button" onclick="Func();" value="Click me" /> <div id="i1" > <div>123</div> <div alex="sb">123</div> <div>123</div> <div alex="sb">123</div> <div>123</div> <!--<input type="text">--> <!--<input type="password">--> <!----> </div> <script> function Func() { // i1 // i1 all children, loop each child, judge if alex='sb' var i1 = document.getElementById('i1'); var divs = i1.children; for(var i=0;i<divs.length;i++){ var current_div = divs[i]; var result = current_div.getAttribute('alex'); // console.log(result); if(result == "sb"){ current_div.innerText = "456"; } } } </script></body></html>Change element values through custom attributesThe above article has a deep understanding of JavaScript DOM objects. This article is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.