DOM Manipulation techniques

Source: Internet
Author: User

Directory

    • Dynamic scripting
    • Dynamic styles
    • Action Form
    • Using NodeList

Dynamic scripting

There are two ways to use the <script> element to insert JavaScript code into a page: include external files through the SRC attribute, and use the element itself to contain the code
Dynamic scripting refers to the absence of a page load and the need to dynamically add scripts by modifying the DOM at some point in the future. As with manipulating HTML elements, there are two ways to create a dynamic script: inserting an external file and inserting the JS code directly.
(1) inserting an external file

// dynamically create <script type= "Text/javascript" src= "Test.js" ></script> var script = document.createelement ("script"= "Text/javascript"; script.src= "Test.js" ;d ocument.body.appendChild (script);//This sentence can be put anywhere

The external file is not downloaded until the last line of code is added to the page of the <script> element. The entire process can be encapsulated with a function:

function loadscript (URL) {   var script = document.createelement (' script ');   Script.type= "Text/javascript";    = URL;   Document.body.appendChild (script);} Loadscript ("test.js");

This script can be used elsewhere on the page when the load is complete. How to know when the script is loaded (from the server request to download) completed, there are some events can be found, but depending on the browser, the support of the poor few browsers.
<script> (in <=ie10 and opera) and <link> (<=ie10 only) element triggers the ReadyStateChange event (inherited from HTMLElement.prototype.onreadystatechange), which can be used to determine whether external JavaScript and CSS files have been loaded. When adding dynamically created elements to the page the browser begins to download external resources, when the readystate attribute of the element, whether equal to "loaded" or "complete", indicates that the resource is already available. Below is a section of loading external JavaScript file code (limited to <=IE10 and running in support of AddEventListener).

function (e) {  var script = document.createelement (' script ');  Script.addeventlistener (function(e) {     if(e.target.readystate = = ' Loaded ' | | E.target.readystate = = ' complete ') {         e.target.removeeventlistener (' ReadyStateChange ', Arguments.callee, FALSE);         Alert (' Script loaded ');     }  });   = ' Example.js ';  Document.body.appendChild (script);}

At this point, get <script src= "Example.js" > The value of the readystate is "loaded", at the same time you can execute the external files already loaded ' example.js ' function.
(2) Insert the JS code directly inside the line (the browser can run except <=IE8)

var script = document.createelement (' script '= ' text/javascript '; Script.appendchild ( document.createTextNode ("function Sayhi () {alert (' Hi ')}");d ocument.body.appendChild (script);

Because <=IE8 treats <script> as a special element and does not allow the DOM to access its child nodes, you can use the <script> The element Text property (inherited from Htmlscriptelement.prototype) specifies the JavaScript code.

// for <=IE8 and Safari3 and later versions var script  = document.createelement (' script '= ' Text/javascript '= "function Sayhi ()} { Alert (' Hi ')} ";d ocument.body.appendChild (script);

Code compatible with all browsers

function loadscriptstring (code) {  var script = document.createelement (' script ');   = "Text/javascript";   Try {   // in addition to <=IE8 and Safari3 and later versions    script.appendchild ( document.createTextNode (code));  } Catch (e) {    = code;  }  Document.body.appendChild (script);}

This is actually the same as executing the code and passing the same string to eval () in the global scope.

Dynamic styles

elements that can incorporate CSS styles into an HTML page are <link> and <style>
(1). A dynamic style is a style that does not exist when the page is loaded, and dynamic styles are added to the page dynamically after the page has been loaded.

function loadstyles (URL) {  var link = document.createelement ("link");   = "stylesheet";   = "Text/css";   = URL;   var head = document.getElementsByTagName (' head ') [0];  Head.appendchild (link);}

The process of loading an external style file is asynchronous, that is, the loading style is not in a fixed order with the process of executing the JavaScript code. Several events can be used to detect whether a style is loaded in <=ie10 and AddEventListener-enabled IE

Window.onload =function(e) {varlink = document.createelement (' link '); Link.type= "Text/css"; Link.rel= "stylesheet"; Link.addeventlistener (' ReadyStateChange ',function(e) {if(E.target.readystate = = ' Loaded ' | | e.target.readystate = = ' complete ') {E.target.removeeventlistener (' ReadyStateChange ', Arguments.callee,false); Alert (' CSS Loaded ');  }  }); Link.href= "Example.css"; document.getElementsByTagName (' head ') [0].appendchild (link);}

At this point, get <link href= "Example.css" > The value of readystate is "complete".
(2). Use the <style> element to include embedded CSS

var style = document.createelement (' style '= ' text/css '; Style.appendchild ( document.createTextNode ("body{background-color:red}"); var head = document.getElementsByTagName (' head ') [0];head.appendchild (style);

The

Same <=IE8 treats <style> as a special, node that is similar to <script> does not allow access to its child nodes. To solve this problem is to access the element's stylesheet attribute (inherited from Htmlstyleelement.prototype), note that this property is only available in <=ie10, other browsers (Chrome and FF) have not been tested, This property points to an instance of a Cssstylesheet type. This instance property inherits the Csstext property of Cssstylesheet.prototype, which can accept CSS code. The test result is IE10 simulation.

compatible with all browser code

function loadstylestring (CSS) {   var style = document.createelement (' style ');    = "Text/css";    Try {      style.appendchild (document.createTextNode (CSS));   } Catch (e) {      = css;   }     var head = document.getElementsByTagName ("head") [0];      Head.appendchild (style);}

Note that after the csstext is set, the value is returned with an uppercase string when accessed through Style.styleSheet.cssText.


Action Form

The HTML Dom also adds properties and methods to the <table>,<tbody>,<tr> element for easy building of tables. Let's take a look at the methods and properties of all of them.
(1) .table.__proto__->htmltableelement.prototype->htmlelement.prototype->element.prototype-> Node.prototype->eventtarget.prototype->object.prototype

    • caption: Holds a pointer to the <caption> element (if any)
    • tbodies: is a <tbody> element of Htmlcollection
    • TFoot: Holds a pointer to the <tfoot> element (if any)
    • tHead: Holds a pointer to the <tHead> element (if any)
    • Rows: Is the htmlcollection
    • createthead () for all rows in a table: creates the <thead> element and automatically places it in the table, returning the <thead> reference. Note that if the THEAD element is already present in the table, then calling Createthead () is not valid, Chrome does not error, returns the THEAD element in the original table, and the other browser has not yet been tested. But there can be more than one THEAD element in a table (via HTML code, Chrome renders nothing wrong), and when the method is called in a table that already has a THEAD element, the first THEAD element in the original table is returned.
    • Createtfoot (): Creates a <tfoot> element and automatically places it in a table, returning the <tfoot> reference. Note the same thing.
    • createcaption (): Creates a <caption> element and automatically places it in a table, returning the <caption> reference. Note the same thing.
    • createtbody (): Creates an <tbody> element and automatically places it in a table, returns the <tbody> reference, and creates tbody multiple times.
    • deletethead (): Delete the <thead> element from the previous.
    • deletetfoot (): Delete <tfoot> elements from the previous
    • deletecaption (): Delete <caotion> element
    • deleterow (POS): Deletes the row at the specified location.
    • InsertRow (POS): Inserts a row at the specified position in the Rows collection, returning the newly inserted row <tr> element

(2) .tbody.__proto__->htmltablesectionelement.prototype->htmlelement.prototype->element.prototype-> Node.prototype->eventtarget.prototype->object.prototype

    • Rows: Preserving the htmlcollection of the lines in the <tbody> element
    • DeleteRow (POS): Delete a row at a specified location
    • InsertRow (POS): Inserts a row into the rows collection at the specified location, returning a reference to the new row being inserted.

(3) .tr.__proto__->htmltablerowelement.prototype->htmlelement.prototype->element.prototype-> Node.prototype->eventtarget.prototype->object.prototype

    • Cells: htmlcollection that holds the cells in the TR element
    • Deletecell (POS): Delete a specified location cell
    • InsertCell (POS): Inserts a cell into the cells collection at the specified location, returning a reference to the newly inserted cell.
//CREATE TABLEvarTable = document.createelement (' table '); Table.border= 1; Table.width= "100%";//Create TbodyvarTbody = document.createelement ("Tbody"); Table.appendchild (tbody);//Create first rowTbody.insertrow (0); tbody.rows[0].insertcell (0); tbody.rows[0].cells[0].appendchild (document.createTextNode ("cell")); tbody.rows[0].insertcell (1); tbody.rows[0].cells[1].appendchild (document.createTextNode ("cell"));//Create second rowTbody.insertrow (1); tbody.rows[1].insertcell (0); tbody.rows[1].cells[0].appendchild (document.createTextNode ("Cell 2,1")); tbody.rows[1].insertcell (1); tbody.rows[1].cells[1].appendchild (document.createTextNode ("Cell 2,2"));//tables are added to the documentDocument.body.appendChild (table);

Using NodeList

NodeList NamedNodeMap Htmlcollection These three sets are dynamic, except for a few cases.
Nodelist:getelementsbyname,childnodes,queryselectorall (Static collection), and so on, are all returned as NodeList instances.
Htmlcollection:getelementsbytagname,getelementsbyclassname,getelementsbytagnamens, Document.forms and so on are returning htmlcollection instances.
NamedNodeMap: Represents a collection of attribute node objects, Ele.attributes returns NAMEDNODEMAP instances

Queries that run in real time when the DOM document is accessed, so the following code causes an infinite loop.

var divs = document.getelementsbytagname (' div '), I,div;  for (i = 0;i< divs.length; i++) {   = document.createelement (' div ');   Document.body.appendChild (div);}

Instead of saving all the collections created in a single list, the browser updates the collection The next time the collection is accessed, and I and divs.length increment each time, resulting in their values never being equal. The correct wording is as follows:

var divs = document.getelementsbytagname (' div '), I,len,div;  for (i = 0,len = Divs.length; i<len;i++) {   = document.createelement (' div ');   Document.body.appendChild (div);}

Reference

JavaScript Advanced Programming

DOM Manipulation techniques

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.