Creating dynamic Dom_javascript techniques based on javascript

Source: Internet
Author: User
Tags border color

Dynamic scripts

We can insert JavaScript code into the page by using the <script> element in the page. There are two ways: one is through the SRC attribute referencing the external JS file, one is to use this element to include a section of JS code. The so-called dynamic script means that the script does not exist when the page is loaded, and at some point in the future, the script is dynamically added by modifying the DOM. As with manipulating HTML elements, there are two ways to create dynamic scripts: inserting external files and inserting JavaScript code directly.

Dynamically loaded external JavaScript code can be executed immediately, such as the following code:

var script = document.createelement ("script");
Script.type = "Text/javascript";
SCRIPT.SRC = "Demo.js";
Document.body.appendChild (script);

As you can see from the results of the above illustration, the above code generates a <script> node in the <body> element:

 
 

Note that the external script file is not downloaded until the last line of code is executed to add <script> to the page.

Another way to specify JavaScript code is in-line mode, for example:

var script = document.createelement ("script");
Script.type = "Text/javascript";
Script.appendchild (document.createTextNode ("function fn1 () {alert (' Hello wolrd! ')} FN1 (); ");

The above code inserts a section of JavaScript code into the <body> element:

<script type= "Text/javascript" >
function fn1 () {alert (' Hello wolrd! ')} fn1 ();

The above code will be followed by a pop-up cue box showing "Hello world!" Text.

In Firefox, Safari, Chrome, and opera browsers, the DOM code for the above operation can be performed normally. However, in older versions of IE browsers, the code could be wrong. The older version of IE browser sees the <script> element as a special element and does not allow the DOM to access its child nodes. However, you can use the Text property of the <script> element to specify the JavaScript code, for example:

var script = document.createelement ("script");
Script.type = "Text/javascript";
Script.text ("function fn1 () {alert (' Hello wolrd! ')} FN1 (); ");

After you have modified the code like this, you can run it in IE, Firefox, Safari3.0, Chrome, and opera browsers. The Safari3.0 browser does not perform the Text property correctly, but you can use a text node to specify the code. So if you need to support older browsers, you can write the code as follows:

var script = document.createelement ("script");
Script.type = "Text/javascript";
var code = "Function Fn1 () {alert (' Hello wolrd! ')} FN1 (); ";
try{
script.appendchild (document.createTextNode (code));
} catch (e) {
script.text = code;
}

The code above first tries the standard DOM text node method, because other browsers support this approach in addition to the older versions of IE browsers. If this line of code throws an exception, then it is an older version of IE, you must use the Text property.

We can encapsulate the code that dynamically adds script into a function, and dynamically load different scripts with different parameters.

function Loadscript (code) {
var script = document.createelement ("script");
Script.type = "Text/javascript";
try{
script.appendchild (document.createTextNode (code));
} catch (e) {
script.text = code;
}
Document.body.appendChild (script);

To call this function, you can look like this:

 
 

The code that is loaded in this way executes in the global scope and is available immediately after the script is executed. In fact, this code of execution is the same as passing the same string to the eval () function in the global scope.

Dynamic style

There are two elements that can typically be included in a CSS style to an HTML page: one is a <link> element that contains files from the outside, and the other is a <style> element that specifies the embedded style. Like dynamic scripts, dynamic styles refer to styles that do not exist when the page is loaded. A dynamic style is a script that is dynamically added to a page after the page has finished loading. For example, the following example:

var link = document.createelement ("link");
Link.rel = "stylesheet"
link.type = "Text/css";
Link.href = "Styles.css";
var head = document.getElementsByTagName ("head") [0];

The above code works in all major browsers. Note that the <link> element is added to the

Also note that the process of loading an external style file is asynchronous, meaning that the process of loading styles and executing JavaScript code is not in a fixed order.

Another way to define a style is to use the <style> element to include embedded CSS styles. For example, the following code:

var style = document.createelement ("style");
Style.type = "Text/css";
Style.appendchild (document.createTextNode ("Body{background: #f00;}"));
var head = document.getElementsByTagName ("head") [0];

The above code can dynamically add the following nodes in the

<style type= "Text/css" >
background: #f00;

The above code works well in Firefox, Safari, Chrome, and opera browsers, and can be an error in an older version of IE. The older version of IE will see the <style> element as a special node and will not allow access to its child nodes. The problem with older IE is to access the stylesheet attribute of the element, which has a csstext property and can accept CSS code. For example, the following code:

var style = document.createelement ("style");
Style.type = "Text/css";
try{
Style.appendchild (document.createTextNode ("Body{background: #f00;}"));
catch (e) {
style.styleSheet.cssText = "Body{background: #f00;}";

Similarly, we can encapsulate code that dynamically adds a style into a function that dynamically loads different styles with different parameters.

function Loadstyle (code) {
var style = document.createelement ("style");
Style.type = "Text/css";
try{
style.appendchild (document.createTextNode (code));
} catch (e) {
style.styleSheet.cssText = code;
}
var head = document.getElementsByTagName ("head") [0];
Head.appendchild (style); 

JavaScript action on a table

In JavaScript, the HTML DOM provides properties and methods for table <table>, <tbody>, and <tr> in order to make it easy to build tables.

The properties and methods of the <table> elements of the table are:

Caption: A pointer to save a reference to a <caption> element.
Tbodies: is a <tbody> element of the htmlcollection.
TFoot: A pointer to save a reference to a <tfoot> element.
THead: A pointer to save a reference to a <thead> element.
Rows: Is the htmlcollection of all the rows in the table.
Createthead (): Creates a <thead> element, puts it in a table, and returns its reference.
Createtfoot (): Creates a <tfoot> element, puts it in a table, and returns its reference.
Createcaption (): Creates a <caption> element, puts it in a table, and returns its reference.
Deletethead (): Delete <thead> element.
Deletetfoot (): Deleting <tfoot> elements
Deletecaption (): Deleting <caption> elements
DeleteRow (POS): Deletes a table row at the specified location.
InsertRow (POS): Inserts a row into the rows collection at the specified location.

The properties and methods of the <tbody> elements of the table are:


Rows: Preserves the htmlcollection of the Bank of <tbody> elements.
DeleteRow (POS): Deletes a table row at the specified location.
InsertRow (POS): Inserts a row into the rows collection at the specified location.

The properties and methods of the <tr> elements of the table are:

Cells: Holds the htmlcollection of the cell in the <tr> element.
Deletecell (POS): Deletes the cell at the specified location.
InsertCell (POS): Inserts a cell into the cells collection at the specified location and returns a reference to the newly inserted cell.

Using these properties and methods above, you can make it easy to use JavaScript to create a table, such as the following code:

Create a table
vatabldocument.createelement ("table");
Table.borde1;
Table.widt "100%";
Create Tbody
vatboddocument.createelement ("tbody");
Table.appendchild (tbody);
Create the first table row
tbody.insertrow (0);
Tbody.rows[0].insertcell (0);
Tbody.rows[0].cells[0].appendchild (document.createTextNode ("Unit 1-1"));
Tbody.rows[0].insertcell (1);
Tbody.rows[0].cells[1].appendchild (document.createTextNode ("Unit 2-1"));
Create a second table row
Tbody.insertrow (1);
Tbody.rows[1].insertcell (0);
Tbody.rows[1].cells[0].appendchild (document.createTextNode ("Unit 1-2"));
Tbody.rows[1].insertcell (1);
Tbody.rows[1].cells[1].appendchild (document.createTextNode ("Unit 2-2"));
Add a table to a document

Use the above code to create a table in the page dynamically. When the table row is created, the Insertcell () method is invoked through the <tbody> element and passed in parameter 0, which indicates where to place the inserted rows. After this line of code is executed, a table row is automatically created and inserted into the 0 position of the <tbody> element, where the newly inserted row can be referenced by tbody.rows[0.

You create cells in the same way that you create table rows. Call the Insertcell () method with the <tr> element and pass in the location where you want to place the cell. You can then refer to the newly inserted cell through tbody.rows[0].cells[0].

About NodeList

Understanding NodeList and NamedNodeMap, Htmlcollection is the key to understanding the DOM as a whole. These 3 collections are dynamic, that is, whenever the document structure changes, they always keep the latest information. Essentially, all NodeList objects are queries that run in real time while accessing a DOM document. For example, the following code causes a dead loop to occur:

var divs = document.getelementsbytagname ("div");
for (var i = 0; i < divs.length i++) {
var div = document.createelement ("div");
Document.body.appendChild (DIV);

The code above first obtains the htmlcollection of all <div> elements and is stored in a variable. Because this collection is dynamic, new <div> elements are added to the collection as long as new <div> is added to the page. The result is that the div.length value is constantly changing, and each loop adds a <div> element to the page, and the value of length increments. In this way I < divs.length conditions will never be established, leading to the occurrence of dead loops.

If we want to iterate over a nodelist, it is best to initialize the length property to the second variable, and then compare the iterator with the variable, for example:

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

Because Len saves a snapshot of the divs.length at the beginning of the loop, it avoids the occurrence of a dead loop.

More examples:

function Salert (str) {var msgw,msgh,bordercolor; msgw=400;//hint window width msgh=100;//tip window Height titleheight=25//Prompt window caption height
Bordercolor= "#c51100";//Prompt window border color titlecolor= "#c51100";//Hint window title color var swidth,sheight;
Swidth=screen.width;
Sheight=screen.height;
var bgobj=document.createelement ("div");
Bgobj.setattribute (' id ', ' bgdiv ');
bgobj.style.position= "Absolute";
bgobj.style.top= "0";
Bgobj.style.background= "#cccccc";
Bgobj.style.filter= "Progid:DXImageTransform.Microsoft.Alpha" (style=3,opacity=25,finishopacity=75);
bgobj.style.opacity= "0.6";
bgobj.style.left= "0";
Bgobj.style.width=swidth + "px";
Bgobj.style.height=sheight + "px";
BgObj.style.zIndex = "10000";
Document.body.appendChild (Bgobj);
var msgobj=document.createelement ("div") Msgobj.setattribute ("id", "msgdiv");
Msgobj.setattribute ("Align", "center");
msgobj.style.background= "White";
Msgobj.style.border= "1px solid" + bordercolor;
MsgObj.style.position = "absolute";
MsgObj.style.left = "50%";
MsgObj.style.top = "50%"; Msgobj.style.font= "12px/1.6Em Verdana, Geneva, Arial, Helvetica, Sans-serif ";
MsgObj.style.marginLeft = " -225px";
MsgObj.style.marginTop = -75+document.documentelement.scrolltop+ "px";
MsgObj.style.width = MSGW + "px";
MsgObj.style.height =msgh + "px";
msgObj.style.textAlign = "center";
MsgObj.style.lineHeight = "25px";
MsgObj.style.zIndex = "10001";
MsgObj.style.position = "absolute";
var Box=document.getelementbyid (str);
var title=document.createelement ("H4");
Title.setattribute ("id", "msgtitle");
Title.setattribute ("Align", "right");
title.style.margin= "0";
Title.style.padding= "3px";
Title.style.background=bordercolor; Title.style.filter= "Progid:DXImageTransform.Microsoft.Alpha (startx=20, starty=20, finishx=100, finishy=100,style=
1,OPACITY=75,FINISHOPACITY=100); ";
Title.style.opacity= "0.75";
Title.style.border= "1px solid" + bordercolor;
Title.style.height= "18px";
Title.style.font= "12px Verdana, Geneva, Arial, Helvetica, Sans-serif";
title.style.color= "White";
title.style.cursor= "Pointer"; Title.onmousedown=function () {StartDrag (this, ' Msgdiv ')};
Title.onmouseup=function () {Stopdrag (this, ' Msgdiv ')};
Title.onmousemove=function () {Drag (' Msgdiv ')};
var closer=document.createelement ("div");
Closer.onclick=function () {Closereturn (); Document.body.appendChild (box); box.style.display = "none";
Document.body.removeChild (Bgobj);
document.getElementById ("Msgdiv"). RemoveChild (title);
Document.body.removeChild (Msgobj);
};
Closer.innerhtml= "OK";
Document.body.appendChild (Msgobj);
document.getElementById ("Msgdiv"). AppendChild (title);
document.getElementById ("Msgtitle"). appendchild (Closer);
box.style.display= "inline";
document.getElementById ("Msgdiv"). appendchild (box);
Showreturn (); }

HTML DOM tree:

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.