DOM basics 2.4 _ JavaScript tips for taking javascript Study Notes

Source: Internet
Author: User
DOM (DocumentObjectModel), that is, "Document Object Model ". Based on the Semantic Logic Structure, DOM presents the elements and content in the webpage as a clear and easy-to-read tree model. The following small series will share with you the DOM basics of recent javascript notes, if you have any need, you can refer to the development of DOM, which is closely related to the general trend of WEB standardization. Only based on the correct semantic logic can DOM play its role correctly. Nowadays, correct semantic structure, performance, and content separation have all become basic requirements in web design. Therefore, in front-end development of web pages, the existence of DOM undoubtedly provides an excellent API for connection at the presentation layer, behavior layer, and even content layer, become an indispensable part of popular Ajax applications.

I. Stable degradation

1. Concepts

In the early days, before JavaScript was used, the content on the webpage could be displayed normally, and users could browse related content through peripherals (such as the mouse). This browsing experience may not be ideal for users.

According to this requirement, the content provider has a reasonable goal-that is, using JavaScript to improve user experience and user stickiness without affecting content presentation.

In this benchmark, there is a very obvious condition that it cannot affect the normal display of the content. In other words, even if the user's browser does not support JavaScript, it can ensure that the user can browse normally.

2. Method

① Separate JavaScript from HTML

This is the first thing we should think of. Let the two separate. HTML is like returning to the status before JavaScript was used in the early days.

For example, you can write an event handler such as element. onClick into JavaScript and bind it with a function.

② Inspect the methods in JavaScript

Some methods mentioned earlier, such as getElementById, need to determine whether the method is supported.

《script》if(! document.getElementById) return false;《script》

The if statement is used to check whether this method is supported. if this method is supported, you can continue. if this method is not supported, false is returned directly. This eliminates the need for effort, it also plays a role in performance optimization.

2. bind an onload event

1. Reason for binding

Some functions can be effectively executed only after the page is fully loaded. We need to bind the function to the window. onload event.

 Yi Yusheng-blog ParkScript function tagAttribute () {var ali = document. getElementsByTagName ('lil'); for (var I = 0; I <ali. length; I ++) {if (ali [I]. firstChild. nodeType = 3) {alert (ali [I]. childNodes [0]. nodeValue) ;}} window. onload = tagAttribute; scriptYu Sheng

The time passes, and the website cannot be renewed for months.

  • JavaScript
  • HTML
  • CSS
  • My Essays

In the above example, if window. onload is not bound, the execution of the tagAttribute function will be meaningless.

Note that the bound function is not the value of the function, so parentheses are not followed.

2. Binding method

If you only need to bind a function, the above method can easily achieve your goal.

window.onload = myFunction;

If there are multiple functions, you may bind them one by one. However, the result is that only the last function can be effectively executed. This is a good understanding of this.

The purpose is that these functions can be effectively executed no matter how many functions are executed when the page is loaded. That is to say, these functions are successfully bound to the window. onload event.

 Yi Yusheng-blog ParkScript function addOnLoadEvent (func) {var oldonload = window. onload; // store the values of the existing window. onload event handler function to the variable oldonload if (typeof window. onload! = 'Function') {// if this handler is not bound to any function window. onload = func; // bind this function to window. onload event} else {window. onload = function () {// if this handler has been bound to a function, append this function to the end of the instruction oldonload (); func ();}}} // custom function tagAttribute // function: Obtain the title value of the li tag function tagAttribute () {var ali = document. getElementsByTagName ('lil'); for (var I = 0; I <ali. length; I ++) {if (ali [I]. childNodes [0]. nodeType = 3) {alert (ali [I]. childNodes [0]. nodeValue) ;}} addOnLoadEvent (tagAttribute); // bind the tagAttribute function to the window. onload event scriptYu Sheng

The time passes, and the website cannot be renewed for months.

  • JavaScript
  • HTML
  • CSS
  • My Essays

Javascript study notes Dom knowledge point summary

The JavaScript window object corresponds to the browser window. Therefore, the attributes and methods of this object are collectively referred to as BOM (Browser object model), such as window. open () and window. location.

JavaScript document object refers to the document Object Model, which is mainly used to process webpage content. DOM (Document Object Model) is a Document Object Model. It is an API for HTML and XML documents. The letter D refers to document, the letter O refers to object, and the letter refers to Model ). DOM depicts a hierarchical node tree. A node represents a connection point. A document consists of nodes. DOM nodes are divided into three types: Element nodes, text nodes (not text content), and attribute nodes.

Get the node name and type

1. The nodeName attribute is used to obtain the node name. The text node returns # text, and the element node returns the label name (equivalent to tagName ). Syntax: target node. nodeName
2. The nodeType attribute is used to obtain the node type. element node: 1, attribute node: 2, and text node: 3. Syntax: target node. nodeType
3. The nodeValue attribute is used to obtain and set the value of a node. Element Node returns null. Syntax: target node. nodeValue

How to obtain element nodes

1. document. getElementById

Returns a unique element node through ID Search.

2. document. getElementsByName

Search by name attribute and return an array of element nodes

3. document. getElementsByTagName

Search by Tag Name and return an array of element nodes

The following three methods are supported by HTML5 DOM, not all browsers (for example, some earlier versions of IE are not supported ).

4. document. getElementsByClassName

Search by class Name of the class Attribute and return an array of element nodes

5. document. querySelector

Obtain the element node using the selector condition, and only return the first element node that meets the condition.

6. document. querySelectorAll

Obtain the element node using the selector condition and return an array of all element nodes that meet the condition. Multiple conditions are separated by commas, indicating that the element to be searched must meet all conditions separated by commas, if an element only meets one of the comma-separated conditions, it is not returned.

Summary: getElementById and querySelector return only one element node, while getElementsByName, getElementsByTagName, getElementsByClassName, and querySelectorAll return an array of element nodes.

Node pointer

1. The childNodes attribute is used to obtain the child nodes of the element node and return the node array. Syntax: parent node. childNodes;

2. The children attribute can be used to obtain valid nodes that ignore blank nodes (in some browsers, blank or line breaks are also a text node ). Syntax: parent node. children;

3. The firstChild attribute can be used to obtain the first subnode of an element, which is equivalent to childNodes [0]. Syntax: parent node. firstChild;

3. The lastChild attribute can be used to obtain the last child node of an element, which is equivalent to childNodes [childNodes. length-1]. Syntax: parent node. lastChild;

4. The previussibling attribute is used to obtain the previous sibling node of the target node. Syntax: target node. previussibling;

5. The nextSibling attribute is used to obtain the last sibling node of the target node. Syntax: target node. nextSibling;

6. The parentNode attribute is used to obtain the parent node of a known node. Syntax: subnode. parentNode;

7. The ownerDocument attribute is used for the root node of the document where the current node is located. It is equivalent to document. Syntax: target node. ownerDocument;

Node operations

1. The createElement method is used to create element nodes. Syntax: document. createElement ('element tag name ');

2. The createAttribute method is used to create an attribute node. Syntax: document. createAttribute ('Property name ');

3. The createTextNode method is used to create a text node. Syntax: document. createTextNode ('text content ');

4. The appendChild method is used to add a subnode to the end of the subnode of the target node (it can be an element node created by createElement or a text node created by createTextNode ). Syntax: parent. appendChild (node to be inserted );

5. The insertBefore method is used to insert a new element node before the target element. The pointer is at the parent level of the target element. Syntax: parent. insertBefore (newElement, targetElement );

6. There is no insertAfter method in DOM, but the following method can be used to simulate insertAfter;

/** NewElement: new element to be inserted * targetElement: Target element */function insertAfter (newElement, targetElement) {var parent = targetElement. parentNode; if (parent. lastChild = targetElement) {/* If the target element is the last child element of the parent, the new element is appended to the parent element, that is, add the new element */parent at the end of the child element of the parent. appendChild (newElement);} else {/* Otherwise, add the new element to the next sibling element */parent between the target element and the target element. insertBefore (newElement, targetElement. nextSibling );}}

7. replaceChild is used to replace an element node. the pointer is at the parent level of the target element. Syntax: parent. replaceChild (replaceElement, targetElement );

8. The cloneChild method is used to clone an element node and pass a Boolean parameter. If the parameter is set to true, the current node and all its subnodes are copied. If the parameter is set to false, the node is paid to the current node. Syntax: Target element. cloneChild (true | false );

9. The removeChild method is used to delete a specified node. Syntax: removeChild (the node to be deleted );

10. The getAttribute method is used to obtain the value of an attribute. Syntax: Target element. getAttribute (element attribute name );

11. The setAttribute method is used to set the value of an attribute. It is created without this attribute. Syntax: Target element. setAttribute (element attribute name, attribute value );

12. The removeAttribute method is used to delete an attribute node. Syntax: Target element. removeAttribute (name of the attribute to be deleted );

DOM operation content

1. The innerHTML attribute is used to obtain and set HTML content. Syntax: Element Node. innerHTML or element node. innerHTML = 'html string ';

2. innerText | the textContent attribute is used to obtain and set text content. FireFox uses textContent to get and set (pay attention to compatibility ). Syntax: Element Node. innerText or element node. innerText = 'html string ';

DOM Operation Style

1. The style attribute is used to obtain and set the row style of the element. Syntax: element. style; the style attribute can only get and set intra-row styles. For style attributes such as font-size, remove-and upper-case the first letter after-. The hump method obtains and sets the style as follows: element. style. fontSize, element. style. backgroundColor

2. the getComputedStyle global method is used to obtain the calculated style. The first parameter is the element node, and the second parameter is the type, such as hover and active pseudo classes. By default, null is passed, some IE versions use the currentStyle attribute to obtain the box. currentStyle. Syntax: window. getComputedStyle (element, type)

3. The className attribute is used to obtain and set the style name of an element. Syntax: element. className

4. Custom addClass () | hasClass () | removeClass () method

// Whether the element contains a certain style function hasClass (element, className) {return !! Element. className. match (new RegExp ('(\ s | ^)' + className + '(\ s | $ )'));} // Add the new style function addClass (element, className) to the element {if (hasClass (element, className) = false) {element. className + = ''+ className;} // function removeClass (element, className) {var currentClass = element. className; if (hasClass (element, className) {currentClass = currentClass. replace (new RegExp ('(\ s | ^)' + className + '(\ s | $)'), ''); // remove spaces currentClass = currentClass. replace (/(^ \ s *) | (\ s * $)/g, ''); element. className = currentClass ;}}

DOM operation location and size

1. The clientWidth attribute is used to obtain the actual width of an element. This value is affected by the scroll bar and the inner margin. The outer margin and the border will not be affected. Syntax:

Element. clientWidth;

2. The clientHeight attribute is used to obtain the actual height of an element. This value is affected by the scroll bar and the inner margin. The outer margin and border will not be affected. Syntax:

Element. clientHeight;

3. The offsetWidth attribute is used to obtain the actual width of an element. This value is affected by the border and the inner margin. The outer margin and the scroll bar are not affected. Syntax:

Element. offsetWidth;

4. The offsetHeight attribute is used to obtain the actual height of an element. This value is affected by the border and the inner margin. The outer margin and the scroll bar are not affected. Syntax:

Element. offsetHeight;

5. The offsetTop and offsetLeft attributes are used to obtain the position of an element relative to the parent level. This value is affected by the margin. Syntax: element. offsetTop |

Element. offsetLeft;

6. The scrollTop and scrollLeft attributes are used to obtain the hidden area size of the scroll bar. You can also set to locate the area (for example, return to the top ). Syntax:

Element. scrollTop | element. scrollLeft | element. scrollTop = 0;

Common simple and fast document attributes and Methods

Document. title is used to obtain the document title.

Document. domain is used to obtain the current domain name

Document. URL is used to obtain the current url path

Document. forms

Document. images

Document. body get body Element Node

Document. compatMode recognition document mode

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.