DOM operations and events in JS

Source: Internet
Author: User
Tags tag name

"DOM tree node"
DOM nodes are divided into three main categories: element node, attribute node, text node;

The text node, attribute node belongs to the child node of the element node. operation, we need to take the element node first, and then operate the child nodes;

You can use the GetElement series method to take the element node.

"View element node"
1. getElementById: Take the unique node through the ID. If the ID name is the same, only the first one is taken.
Getelementsbyname (): By Name property
getElementsByTagName (): Signed by label
Getelementsbyclassname (): by class name

>>> when acquiring an element node, it is important to note that the statement that gets the node must be executed after DOM rendering is complete. It can be implemented in two ways: ① writes the JS code after the body, and ② writes the code into the Window.onload function;

>>> after three getelements, the array format is taken. Instead of adding a variety of properties directly, you should remove each individual action of the array. Example: Getelementsbyname ("name1") [0].onclick = function


"View/Set attribute node"
1. View attribute node: getattribute ("attribute name");
2, set the attribute node: setAttribute ("attribute name", "New attribute value");

>>> view and set attribute nodes, you must first take the element node before you can use it.
>>> SetAttribute (); the function may have compatibility problems in IE browser. For example, the use of this function in IE is not supported to set style attributes such as Style/onclick and event properties.

>>> we recommend using dot notation instead of the above function:
Eg:dom1.style.color= "" dom1.onclick= "" dom1.src= ""


"Summary-js Modify the style of the DOM node"
1, use setattribute () to set the class and style properties, but there is a compatibility problem, do not advocate
Div.setattribute ("Class", "cls1");

2. Use. classname directly set class, note that it is classname instead of. Class:
Div.classname = "CLS1";

3. Use the. style to set a single property, and note that the name of the property is used for hump naming:
Div.style.backgroundColor = "Red";

4. Use. Style or. Style.csstext to set multiple style properties:
Div.style = "background-color:red; Color:yellow; "
Div.style.cssText = "background-color:red; Color:yellow; "√


"View Settings text node"
1. InnerText: Take or set the text content of the node;
. InnerHTML: Takes or sets the HTML code inside the node;
. TagName: Takes the label name of the current node. The label name is displayed in all uppercase.

Get nodes by hierarchy
1. ChildNodes: Gets all the child nodes of the element. Includes a text node such as a carriage return.
. Children: Gets all the element nodes of the current element (get labels only).

2. FirstChild: Gets the first child node of an element. Includes a text node such as a carriage return.
. Firstelementchild: Gets the first child node of an element. Text nodes such as carriage return are not included.
. LastChild: Gets the last child node of the element. Includes a text node such as a carriage return.
. Lastelementchild:

3. ParentNode: Gets the parent node of the current node.

4. PreviousSibling: Gets the previous sibling node of the current node, including a text node such as a carriage return.
. previouselementsibling:

5. NextSibling: Gets the next sibling node of the current node, including a text node such as a carriage return.
. nextelementsibling:

6. GetAttributes: Gets the properties node of the current node.

"Create and add a node"
1. Document.createelement ("tag name"): Create node. A variety of new properties need to be set with setattribute;
2. Parent node. appendchild (New node): Insert node at end Append mode
3. Parent node. insertbefore (new node, target node): Inserts a new node before the target node.
4. Cloned node. CloneNode (True/false): Clone node
>>> passed in true: Represents the clone of the current node, as well as all child nodes of the current node;
>>> false or no pass: Indicates that only the current node is cloned, not child nodes.

"Delete or replace nodes"
1. Parent node. RemoveChild (truncated): Removes child nodes from the parent node;
2. Parent node. ReplaceChild (new node, old node): Replace the old node with the new node. \ n
3. Node. RemoveAttribute ("Properties"): Delete properties.

[Table Object]
1, Rows property: Returns all rows in the table, is an array format;
2, InsertRow (index): Insert a row at the specified position, index starting from 0;
3, DeleteRow (index): Delete the specified line, index starting from 0;

[Row Object]
1. Cells property: Returns all cells in this row, is an array format;
2, rowindex property: Return This line is the first line in the table, starting from 0;
3, InsertCell (index): In this line to specify the position, insert a cell, index starting from 0;
4, Deletecell (index): Delete the specified cell of this line, index starting from 0

[Cell Object]
1. CellIndex property: Returns this cell is the first number of the bank, starting from 0;
2, InnerText InnerHTML align ClassName

"Event classification in JS"
1. Mouse events
Click/dblclick/onmouseover/onmouseout

2. HTML Events
Onload/onscroll/onsubmit/onchange/onfocus

3. Keyboard events
KeyDown: Triggered when the keyboard is pressed
KeyPress: Instant trigger when keyboard is pressed and released
KeyUp: Triggered when the keyboard is lifted

[Precautions]
① Execution Order:keydown->keypress->keyup->
② when long on time, will loop to execute keydown->keypress
③ has KeyDown does not necessarily have KeyUp, when the event is triggered, the mouse cursor
Removal will result in no keyup;
④keypress can only capture numbers, characters, and symbol keys on the keyboard, and cannot capture various
function keys, while KeyDown and KeyUp can.
⑤keypress supports case sensitivity, KeyDown and KeyUp are not supported.

[OK button to trigger]
① in the triggered function, a parameter e is passed in to indicate the keyboard event;
② uses E.keycode, takes the ASCII code value of the key, and then determines the trigger button;
③ compatibility of all browsers (not normally required):
var evn = e | | Event
var code = Evn.keycode | | Evn.which | | Evn.charcode;

"The DOM0 event model in JS"
1, inline model (inline binding): The function name directly as an attribute value of an event attribute of an HTML tag;
Eg:<button onclick= "func ()" >dom0 Inline model </button>
Cons: Violate the basic principles of HTML and JavaScript separation;

2, the script model (dynamic binding): In the JS script, take a node, and add the event properties;
Eg:window.onload = function () {}
Advantage: the separation of HTML and JavaScript is realized.
Cons: The same node can only bind one type of event. If the binding is multiple, the last one takes effect.

"DOM2 Event Model"
1, Add Event binding method:
①IE8 Before: btn2[2].attachevent ("onclick", function);
② Other browsers: Btn2[2].addeventlistener ("click", Function, True/false);
Parameter three: false (default) indicates event bubbling true indicates event capture
③ compatible notation: if (btn2.attachevent) {
Btn2[2].attachevent ();
}else{
Btn2.addeventlistener ();
}
2, Advantages: ① can give the same node, add more than one type of event;
② provides functions that can cancel event binding;

3. Cancel the DOM2 event binding:
Note: If you want to cancel the DOM2 event binding, the handler must use the named function instead of the anonymous function when binding the event.
Btn[2].removeeventlistener ("click", Func2);
Btn[2].detachevent ("onclick", FUNC2);

"stream of events in JS"

1. Event bubbling: When a DOM element triggers an event, it starts from the current node and progressively
The same type of event that triggers its ancestor nodes upwards, until the DOM root node;

>>> what happens when event bubbling occurs?
①DOM0 model binding events, all of which are bubbling;
Before ②IE8, the events that were bound with the attachevent () were all bubbling;
③ other browsers, use AddEventListener () to add an event when the third parameter
The event bubbles when omitted or false;

2. Event capture: When a DOM element triggers an event, it starts from the document root node, descending
The same type of event that triggers its ancestor node until the node itself;

>>> what happens when event capture is triggered?
Use AddEventListener () to add an event, which is captured when the third argument is omitted or true;


3. Block Event bubbling:
In Internet Explorer, use e.cancelbubble = true;
In other browsers, use E.stoppropagation ();

Compatible with all browsers:
function Myparagrapheventhandler (e) {
E = e | | window.event;
if (e.stoppropagation) {
E.stoppropagation (); Outside IE
} else {
E.cancelbubble = true; Before IE8
}
}

4. Canceling event default behavior
In Internet Explorer, use E.returnvalue = false;
In other browsers, use E.preventdefault ();

Compatible with all browsers:
function EventHandler (e) {
E = e | | window.event;
Prevent default behavior
if (E.preventdefault) {
E.preventdefault (); Outside IE
} else {
E.returnvalue = false; Ie
}
}

DOM operations and events in JS

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.