This time I will bring you a summary of JS’s Dom and events, a summary of JS’s Dom and eventsWhat are the things to note?The following is a practical case, let’s take a look.
What is the difference between innerText and innerHTML of dom object?
innerHTML refers to the entire content from the starting position to the ending position of the object, including the Html tag .
innerText refers to the content from the starting position to the ending position, but it removes the Html tag.
What is the difference between elem.children and elem.childNodes?
Node (node) is the common name for any type of object in the DOM hierarchy. There are many types of Node, such as element nodes, attribute nodes, text nodes, comment nodes, etc. Element inherits the Node class, which means that Element is one of the many types of Node. That is, when NodeType is 1, Node is ElementNode. In addition, Element extends Node, and Element has attributes such as id, class, and children. children is an attribute of Element, and childNodes is an attribute of Node.
How many common methods are there to query elements?
There are three common ways to obtain elements, namely through element ID, through tag name and through class name.
1.getElementById
DOM provides a method called getElementById, which will return a node object corresponding to the id attribute.
2.getElementsByTagName
This method returns an array of objects (HTMLCollection to be precise, it is not an array in the true sense). Each object corresponds to a given tag in the document. of an element. Similar to getElementById, this method only provides one parameter, and its parameter is the name of the specified tag.
3.getElementsByClassName
In addition to obtaining elements by specifying tags, DOM also provides the getElementsByClassName method to obtain elements with specified class names.
How to create an element? How to set attributes to elements?
1.createElement(name) creates an element node
createElement() is a method in the Document object. This method returns an Element object based on the specified element name.
2. Set the attributes of the created element node
After creating the element, we may need to set the element attributes, such as setting CSS styles for the element, adding click events, etc. To set element attributes, you can use the setAttribute method of the Element object, or you can use the attribute name to set it.
3. Insert the element node into the specified position of the DOM document
After the element is created, you need to insert the element node into the specified position of the DOM document. To add an element, use the appendChild() method or insertBefore() method of the Element object. The appendChild()
method is to add a new child node to the element, and the added child node will be its last child node. The insertBefore() method is used to insert a new node before the existing node, and the added node will be a sibling node.
Adding or deleting elements?
Adding elements: Use createElement to add elements
Deleting elements: If you need to delete an HTML element, you must first obtain the parent element of the element, and then use removeChild to delete the corresponding element.
What is the difference between DOM0 events and DOM2 level event listening methods?
DOM0 event: DOM0 event refers to binding the event directly to the node. A node can only bind one event, otherwise the gray behind it will cover the previous one.
var oBtn = document.querySelctor('#btn');
oBtn.onclick=function(){
console.log('a')
};
DOM2 event: DOM2 Level events can bind multiple events to an element, and subsequent events will not overwrite previous events; you can use the parameters true and false to set the event to trigger in the bubbling phase or capture phase. Use removeEventListener to remove events.
oBtn.addEventListener("click",function(){
});
oBtn.removeEventListener("click",fn,false);
What is the difference between attachEvent and addEventListener?
1. Compatibility issues between addEventListener and attachEvent
addEventListener is an event binding method that complies with W3C specifications. FireFox, Chrome, and Safari all use it to bind events.
attachEvent is private to IE and does not comply with W3C specifications. Moreover, under IE, it can only be used to bind events, and addEventListener is invalid.
So, if you want to bind events, you must deal with compatibility issues.
2. Grammar rules for addEventListener and attachEvent
addEventListener has 3 parameters: element.addEventListener(type,listener,useCapture)
attachEvent has 2 parameters: element.attachEvent(type,listener);
3. Code compatibility processing
function regEvent(ele, event_name, fun)
{
if (window.attachEvent)
ele.attachEvent(event_name, fun); //IE browsing Device
else
{
event_name = event_name.replace(/^on/, “”); //If it starts with on, delete on, such as onclick->click
ele. addEventListener(event_name, fun, false); //Non-IE browser
}
}
Explain IE event bubbling and DOM2 event propagation mechanism?
IE event bubbling: The event occurs on the triggering element. Starting from the triggering element, the event is passed level by level to the parent element until the html element.
DOM2 events: Event propagation is divided into 3 stages, the capture stage, the event target stage, and the bubbling stage. The event listener can only choose to execute in one of the capture phase or the bubbling phase.
Capture phase: When an event occurs, it starts from the root node and searches down level by level to know the target element.
Bubbling stage: Starting from the triggering element, the event is passed level by level to the parent element until the html element
How to prevent event bubbling? How to prevent default event?
Prevent event bubbling: w3c’s method is e.stopPropagation(), and IE uses e.cancelBubble = true.
Prevent default events: w3c’s method is e.preventDefault(), and IE uses e.returnValue = false.
Q&A
There is the following code, which requires the console to display the text content of each element li when the element is clicked. Compatibility with
<ul class="ct"> <li>这里是</li> <li>饥人谷</li> <li>前端6班</li> </ul> <script> //todo ... </script>
is not considered Code:
<ul class="ct"> <li>这里是</li> <li>饥人谷</li> <li>前端6班</li> </ul> <script> //方法一 /*var item = document.getElementsByClassName("ct")[0].getElementsByTagName('li') for(var i=0;i<item.length;i++){ item[i].addEventListener('click', function(){ console.log(this.innerText); }) } */ //方法二 var item = document.getElementsByTagName('li') for(var i=0;i<item.length;i++){ item[i].addEventListener('click', function(){ console.log(this.innerText); }) } </script>
Completion code, requirements:
1. When clicking the button to add at the beginning, here is< ;/li> Add a new element before the element, the content is a non-empty string entered by the user; when clicking the end to add, add the user input after
2. When each element li is clicked, the console displays the text content of the element.
<ul class="ct"> <li>这里是</li> <li>555</li> <li>666</li> </ul> <input class="ipt-add-content" placeholder="添加内容"/> <button id="btn-add-start">开头添加</button> <button id="btn-add-end">结尾添加</button> <script> //todo ... </script>
Code:
<ul class="ct"> <li>这里是</li> <li>666</li> <li>555</li> </ul> <input class="ipt-add-content" placeholder="添加内容"/> <button id="btn-add-start">开头添加</button> <button id="btn-add-end">结尾添加</button>
<script>var ct = document.querySelector('.ct')var start = document.getElementById('btn-add-start');var end = document.getElementById('btn-add-end');var input = document.querySelector(".ipt-add-content"); end.addEventListener('click',function(){ var list = document.createElement('li'); list.innerText = input.value ct.appendChild(list); }) start.addEventListener('click',function(){ var list = document.createElement('li'); list.innerText = input.value ct.insertBefore(list,ct.firstChild); }) ct.addEventListener('click', function(e){ if(e.target.tagName.toLowerCase() === 'li'){ console.log(e.target.innerText); } }); </script>
Complete the code, requirement: when the mouse is placed on the li element, the data-img of the current li element will be displayed in img-preview corresponding picture.
<ul class="ct"> <li data-img="1.png">鼠标放置查看图片1</li> <li data-img="2.png">鼠标放置查看图片2</li> <li data-img="3.png">鼠标放置查看图片3</li> </ul> <div class="img-preview"></div> <script> //todo ... </script>
Code:
<ul class="ct"><li data-img="http://img5.imgtn.bdimg.com/it/u=3425851328,2681317699&fm=21&gp=0.jpg">鼠标放置查看图片1</li><li data-img="http://pic24.nipic.com/20121003/10754047_140022530392_2.jpg">鼠标放置查看图片2</li><li data-img="http://img2.3lian.com/img2007/4/22/303952037bk.jpg">鼠标放置查看图片3</li></ul><div class="img-preview"></div><script>var ct = document.querySelector('.ct')var list = document.getElementsByTagName('li')var preview = document.querySelector('.img-preview')for(var i=0;i<list.length;i++){list[i].addEventListener('mouseover',function(){if(document.querySelector('img')){preview.removeChild(document.querySelector('img'))console.log(1)}var item = document.createElement('img')var img = this.getAttribute('data-img')preview.appendChild(item)item.src=img; }) } </script>
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Related reading:
How to use python to determine image similarity
Javascript script used to download images
The above is the detailed content of Summary of JS Dom and events. For more information, please follow other related articles on the PHP Chinese website!

HTML is not only the skeleton of web pages, but is more widely used in many fields: 1. In web page development, HTML defines the page structure and combines CSS and JavaScript to achieve rich interfaces. 2. In mobile application development, HTML5 supports offline storage and geolocation functions. 3. In emails and newsletters, HTML improves the format and multimedia effects of emails. 4. In game development, HTML5's Canvas API is used to create 2D and 3D games.

TheroottaginanHTMLdocumentis.Itservesasthetop-levelelementthatencapsulatesallothercontent,ensuringproperdocumentstructureandbrowserparsing.

The article explains that HTML tags are syntax markers used to define elements, while elements are complete units including tags and content. They work together to structure webpages.Character count: 159

The article discusses the roles of <head> and <body> tags in HTML, their impact on user experience, and SEO implications. Proper structuring enhances website functionality and search engine optimization.

The article discusses the differences between HTML tags , , , and , focusing on their semantic vs. presentational uses and their impact on SEO and accessibility.

Article discusses specifying character encoding in HTML, focusing on UTF-8. Main issue: ensuring correct display of text, preventing garbled characters, and enhancing SEO and accessibility.

The article discusses various HTML formatting tags used for structuring and styling web content, emphasizing their effects on text appearance and the importance of semantic tags for accessibility and SEO.

The article discusses the differences between HTML's 'id' and 'class' attributes, focusing on their uniqueness, purpose, CSS syntax, and specificity. It explains how their use impacts webpage styling and functionality, and provides best practices for


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver CS6
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

WebStorm Mac version
Useful JavaScript development tools
