JavaScript notes (browser-DOM operations), javascriptdom

Source: Internet
Author: User

JavaScript notes (browser-DOM operations), javascriptdom
1 Browser

Pay attention to the identification of various domestic browsers, such as XX Security browser and XX tornado browser. They only make a shell, and the core of their calls is IE, there are also "dual-core" browsers that support both IE and Webkit.
The main difference between different browsers in JavaScript support is that some APIs have different interfaces, such as AJAX and File interfaces. For the ES6 standard, different browsers have different support for different features.
When writing JavaScript, you must fully consider the differences between browsers and try to make the same JavaScript code run in different browsers.

2 window object

JSHost ObjectThe most basic is the window object. The properties and methods of this object are usually calledBOM (Browser Object Model).

JavaScript can obtain and operate many objects provided by the browser.
windowThe object not only acts as a global scope, but also representsBrowser window.windowOfinnerWidthAndinnerHeightAttributeYou can obtainInternalWidth and height.
There are many attribute methods for window objects. The following lists some common methods:

2.1 attribute instance
  • Screen:screenObject contains the user'sScreen Information, CommonAttributeInclude:screen.widthScreen width,screen.heightScreen height, etc.
  • Navigator:navigatorObject RepresentationBrowser Information, The most commonAttributeIncluding:
    • Navigator. appName: browser name;
    • Navigator. appVersion: browser version;
    • Navigator. language: The language set by the browser;
    • Navigator. platform: operating system type;
    • Navigator. userAgent: the User-Agent string set by the browser.
    • Note:Browser information can be easily modified by users
  • Location:locationObject RepresentationURL Information of the current page, The most commonAttributeIncluding:
    • Location. href: complete URL
    • Location. protocol: protocol
    • Location. host: website name, 'www .example.com'
    • Location. port: port, '123'
    • Location. pathname: path,/path/index.html'
    • To load a new page, call location. assign (url).
    • To reload the current page, call location. reload ().
  • History: record the browser history and callhistory.back()Return to the previous page and callhistory.forward()Return to the previous step.
  • Document:documentObjectIndicates the current pageIn the browser, HTML is represented as a tree structure in the form of DOM.documentThe object is the root node of the entire DOM tree.documentAnother objectcookieTo obtain the Cookie of the current page.
    Cookie is the key-value identifier sent by the server.. Because the HTTP protocol is stateless, the server can use cookies to identify which user sends the request. After a user successfully logs on, the server sends a Cookie to the browser, for example, user = ABC123XYZ (encrypted string )..., After that,When the browser accesses the website, the Cookie is attached to the request header, and the server can distinguish users based on the Cookie.. (The server can usehttpOnly, SethttpOnlyThe Cookie cannot be read by JavaScript)
2.2 Method
  • alert(str): Pop-up message box
  • confirm(str): Used to pop up the select confirm message box
  • prompt(str): Pop-up text input message box
  • open(url,name,features): The url is required. The last two are optional,nameThere are three special values used to define how to open a webpage window, such_topIt refers to opening after the current window of the entire browser is replaced,_targetIndicates re-opening a new browser window page,_selfIndicates that the current small window is opened.featuresDefine the widget when a window is opened
  • close(): Close the current page
  • setTimeout(func,time): The number of seconds after which the function will be executed. Note: Do not add brackets to the first parameter.
  • cleaarTimeout(id): Cancel the timer operation.setTimeout(func,time)Assign a value to a variable whose name isid
  • setInterval(func,time): The number of times at which the function is executed
  • clearInterval(id): Cancel Timer
3. Operate DOM

After the HTML Document is parsed by the browser, It is a DOM tree (Document Object Modle ).What the browser actually shows is the DOM tree of this course..
JavaScript can operate on a DOM node. operations on a DOM node are actually the following operations:

  • Update: Update the content of the DOM node, which is equivalent to updating the HTML content represented by the DOM node;
  • Traversal: Traverses sub-nodes under the DOM node,For further operations;
  • Add: Add a subnode under the DOM node, which is equivalent to dynamically adding an HTML node;
  • Delete: Deleting a node from HTML is equivalent to deleting the content of the DOM node and all its subnodes.
3.1 History DOM nodes

DOM nodes include element nodes, text nodes, and attribute nodes.Attribute nodes must be included in element nodes, while most text nodes are element nodes.Subnode.

You must obtain this node before operating the node.documentObject properties.document.getElementsBy..This form, such:

/* Js naming: Common variables are underlined, while function names, method names, and object attribute names are commonly named using the camel naming method */var a = document. getElementById ("idname"); // note that the Element is not followed by s, because the id corresponds to only one var B = document. getElementsByClassName ("classname"); // Add s. Note that when you want to select element nodes with multiple class names, the class names can be separated by spaces. var c = document. getElemantsByTagName ("tagname"); // Add s

document.getElementsByTagName()Anddocument.getElementsByClassName()Always returnA group of DOM nodesIn this case, you canUse IndexTo narrow down the scope (The search parameters can be written as wildcards.*).
In addition:

  • Node.childNodes.
  • Node.firstChild: First subnode
  • Node.lastChild: Last subnode
  • Node.parentNode: Parent node
  • Node.nextSibling: Return the sibling node that follows it, but does not returnnull
  • Node.proviousSibling: Returns the previous sibling node. Nonull

How can I filter out blank text when a group of subnodes are returned?
This requires the following node attributes:

  • Node.nodeType: This returns a number, where "element" Returns number 1, that is, it can be used to filter out blank text.
  • Node.nodeName: If it is an "element", the element name, such as a paragraph, is returned.p

For more information, see:

3.2 update DOM

Get a DOM node, you canIts AttributesModify and update.

3.2.1 HTML

ModifyinnerHTMLAttribute,innerHTMLAttributes can not only modify HTML element text, but also change the internal structure of elements.

// Obtain <p id = "sei"> 123 </p> var p = document. getElementById ("sei"); // modify the text p. innerHTML = "ABC"; // Changes to <p> ABC </p> // modifies the structure p. innerHTML = "ABC <span> 123 </span>"; // Changes to <p> ABC <span> 123 </span> </p>

ModifyinnerTextOrtextContentAttribute, Only text can be changed, and the structure cannot be modified:

p.innerText="ABC";p.textContent="ABC";
3.2.2 CSS

DOM NodestyleAttribute corresponds to all CSS, which can be directly obtained or set, but somefont-sizeThe name will be automatically convertedHump namingfontSize.

p.style.color="deeppink";p.style.fontSize="small";
3.3 insert DOM

Get a DOM node, you can use its method to insert a DOM node.

3.3.1 appendChild

DOM node usageappendChild()Method, you can setA dom node is placed at its end..

/* <Div id = "list"> <p id = "java"> Java </p> <p id = "JavaScript"> JavaScript </p> <p id = "scheme"> Scheme </p> </div> * // For example, to create a python section, place it under the list module. // Create a JavaScript section var python = document. createElement ("p"); // create a paragraph element python. id = "python"; // bind idpython. innerText = "python" // bind text // place it under the listt module. Var list = document. getElementById ("list"); // obtain the node list. apppendChild (python); // Method for running nodes, insert a node at the end/* the DOM document tree <div id = "list"> <p id = "java"> Java </p> <p id = "JavaScript"> JavaScript </p> <p id = "scheme"> Scheme </p> <p id = "python"> python </p> </div> */
3.3.2 insertBefore

The precedingappendChildOnly the end can be inserted.insertBeforeNow,insertBeforeThe usage is,First, you must obtain the positioning node and its parent node, and insert the byte itself, and then callinsertBeforeMethod, Syntax:
parentElement.insertBefore(newElement, referenceElement);NewElement is placed before referenceElement.

/* Insert a C */var c = document in front of JavaScript in the document tree above. createElement ("p"); c. innerText = "C"; c. id = "C"; var JavaScript = document. getElementById ("JavaScript"); list. insertBefore (c, JavaScript); // c is in front

Note:

  • Usedocument.createElement(str);, Str is the HTML element name.
  • Then bind some attributes, such as id, innerText, andsetAttribute, Suchd.setAttribute('type', 'text/css');
3.4. Delete DOM

To delete a node,First obtain the node itself and its parent node, and then callremoveChildDelete yourself.

// Get the node to be deleted: var self = document. getElementById ('to-be-removed'); // obtain the parent node: var parent = self. parentElement; // Delete: parent. removeChild (self );

Note:When traversing a child node of a parent node and performing the delete operation, be careful when calling the children attribute. The children attribute is also being deleted.
You can usewhileStatement

Top
0
Step on
0
View comments

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.