Sort out common operations of JavaScript on various types of elements in DOM, including javascriptdom

Source: Internet
Author: User

Sort out common operations of JavaScript on various types of elements in DOM, including javascriptdom

Node Type
NodeType
The following are some important nodeType values:
1: element
2: attr
3: text
8: Comment comments
9: document

NodeName, nodeValue

Node relationship
ChildNodes: each node has a childNodes attribute, which stores a NodeList object.

FirstChild: equivalent to childNodes [0]

LastChild: equivalent to childNodes. length-1

You can also access other nodes in the same list by using the previussibling and nextSibling attributes of each node in the list.

Operation Node
AppendChild ()

The appendChild () method is used to add a node to the end of the childNodes list. After a node is added, the new node, parent node, and the link pointer of the previous child node of childNodes are updated accordingly.

InsertBefore ()
The insertBefore () method accepts two parameters: the node to be inserted and the node to be referenced.

// Insert and become the last subnode returnedNode = someNode. insertBefore (newNode, null); // after being inserted, it becomes the first node returnedNode = someNode. insertBefore (newNode, someNode. firstChild); // insert it to the front of the last subnode returnedNode = someNode. insertBefore (newNode, someNode. lastChild );

RepaceChild ()
RepaceChild () accepts two parameters: the node to be inserted and the node to be replaced

var returnedNode = someNode.replaceChild(newNode,someNode.firstChild);

RemoveChild ()
Only remove rather than replace nodes.

var formerFirstChild = someNode.removeChild(someNode.firstChild);

CloneNode ()

Item 1
Item 2
Item 3

var deepList = myList.cloneNode(true);console.log(deepList.length); // 3var shallowList = myList.cloneNode(false);console.log(shallowList.childNodes.length); //0

Document Type

The Document node has the following features:

  • The value of nodeType is 9;
  • The value of nodeName is # document;
  • The nodeValue is null;
  • The value of parentNode is null;
  • The ownerDocument value is null;

Sub-nodes of the document

Var html = document.doc umentElement; // obtain the reference console for 

Document Information

// Obtain the document title var originalTitle = document. title; // set the document title document. title = "New page title"; // obtain the complete urlvar url = document. URL; // obtain the domain name var domain = document. domain; // obtain the urlvar referrer = document. referrer; // assume that the page is from the p2p.wrox.com domain document. domain = "wrox.com"; // document succeeded. domain = "nczonline.net"; // failed

Call document. getElementById ("myElement") in IE7. The <input> element is returned, as shown below;
The best way is to prevent the name attribute of the form field from being the same as the ID of other elements.

<input type="text" name="myElement" value="text field"><div id="myElement">a div</div>

Special set

  • Document. anchors, which contains all the elements with the name feature in the document;
  • Document. forms: contains all form elements in the document. The result is the same as that obtained by document. getElementsByTagName ("form;
  • Document. images, which contains all the img elements in the document, returns the same result as document. getElementsByTagName ("img;
  • Document. links, which contains all elements a with the href feature in the document;

Document Writing

The string <\/script> is not used as the close tag of the external script tag, so there will be no additional content on the page.

Element type
Element nodes have the following features:

  • The value of nodeType is 1;
  • The value of nodeName is the Tag Name of the element;
  • The nodeValue is null;
  • ParentNode may be a Document or Element;

You can use the nodeName attribute or the tagName attribute to access the tag name of an element;

<Div id = "myDiv"> </div> var div = document. getElementById ("myDiv"); console. log (div. tagName); // DIVconsole. log (div. nodeName); // DIVif (element. tagName = "div") {// cannot be compared like this, it is easy to make an error} if (element. tagName. toLowerCase = "div") {// This is best (applies to any document )}

Obtain features
There are three DOM methods for operating features: getAttribute (), setAttribute (), and removeAttribute ();
Note that the feature name passed to getAttribute () is the same as the actual feature name. To get the feature value of the class, you should input "class" instead of "className ".

var div = document.getElementById("myDiv");console.log(div.getAttribute("class")); // bd

Create Element
You can use the document. createElement () method to create new elements.

Child node of the element
Before performing an operation, you usually need to check the nodeType attribute, as shown in the following example:

For (var I = 0; len = element. childNodes. length; I <len; I ++) {if (element. childNodes [I]. nodeType = 1) {// perform some operations }}

Text Type
Text nodes have the following features:

  • The value of nodeType is 3;
  • The value of nodeName is "# text ";
  • The value of nodeValue is the text contained in the node;
  • ParentNode is an Element;

Create a text node
You can use document. createTextNode () to create a new text node.

Normalize text nodes
Normalize ()

Split text nodes
SplitText ()

Comment type
Comment nodes have the following features:

  • The value of nodeType is 8;
  • The value of nodeName is "# comment ";
  • The value of nodeValue is the content of the comment;
  • ParentNode may be a Document or Element;
  • Sub-points are not supported (none;

DOM operating technology
Operation table

// Create tablevar table = document. createElement ("table"); table. border = 1; table. width = "100%"; // create tbodyvar tbody = document. createElement ("tbody"); table. appendChild (tbody); // create the first tbody. insertRow (0); tbody. rows [0]. insertCell (0); tbody. rows [0]. cells [0]. appendChild (document. createTextNode ("cell 1, 1"); tbody. rows [0]. insertCell (1); tbody. rows [0]. cells [1]. appendChild (document. createTextNode ("cell"); // create the second line of tbody. insertRow (01); tbody. rows [1]. insertCell (0); tbody. rows [1]. cells [0]. appendChild (document. createTextNode ("cell 1, 2"); tbody. rows [1]. insertCell (1); tbody. rows [1]. cells [1]. appendChild (document. createTextNode ("cell 2, 2"); document. body. appendChild (table );

Selector API
QuerySelector () method

// Obtain the body element var tbody = document. querySelector ('body'); // obtain the element var myDIV = document whose ID is "myDIV. querySelector ("# myDiv"); // obtain the first element var selected = document whose class is "selected. querySelector (". selected "); // obtain the first image element var img = document whose class is" button. body. querySelector ("img. button ");

QuerySelectorAll () method

// Obtain all <em> elements in a <div> (similar to getElementsByTagName ("em") var EMS = document. getElementById ("myDiv "). querySelectorAll ("em"); // obtain all the elements of the class "selected" var selecteds = document. querySelectorAll (". selected "); // obtain all <strong> element var strongs = document. querySelectorAll ("p strong ");

HTML5
Class-related extensions
GetElementsByClassName () method:
This method can be called through the document Object and all HTML elements.

// Obtain all elements in the class that contain "username" and "current. The order of class names does not matter var allCurrentUsernames = document. getElementsByClassName ("username current"); // obtain all the elements with class name "selected" in the element with ID "myDiv" var selected = document. getElementById ("myDiv "). getElementsByClassName ("selected ");

Focus Management

HTML5 also adds the function to help manage DOM focus. The first is the document. activeElement attribute, which always references the element that currently gets the focus in the DOM.

var button = document.getElementById("myButton");button.focus();alert(document.activeElement === button); // true

By default, when the document is loaded, the reference of the document. body element is saved in document. activeElement. The docuemnt. activeElement value is null during document loading.
The document. hasFocus () method is added to determine whether the document gets the focus.

var button = document.getElementById("myButton");botton.focus();alert(document.hasFocus()); // true

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.