Dom manipulating tables and styles
Learning Essentials:
1. Operation form
2. Operation Style
The DOM is more concise when it is manipulated to generate HTML. However, because browsers always have compatibility and traps, the final operation is not so
It's simple and convenient. This chapter focuses on some knowledge of DOM operations tables and styles.
First, Operation form
The <table> tag is the most complex structure in HTML, and we can create it using the DOM, or the HTML DOM to manipulate it. (
The ps:html DOM provides a more convenient and quick way to manipulate HTML, with manuals.
Need to manipulate table
<table border = "1" width = ">"
<caption> Staff Table </caption>
<thead>
<tr>
<td> name </td>
<td> Sex </td>
<td> Age </td>
</tr>
</thead>
<tbody>
<tr>
<td> Zhang San </td>
<td> Men </td>
<td>20</td>
</tr>
<tr>
<td> John Doe </td>
<td> Men </td>
<td>21</td>
</tr>
</tbody>
</table>
Use the DOM to create this table
var table = document.createelement (' table ');
Table.border = 1;
Table.width = 300;
var caption = document.createelement (' caption ');
Table.appendchild (caption);
Caption.appendchild (document.createTextNode (' Personnel table '));
var thead = document.createelement (' thead ');
Table.appendchild (THEAD);
var tr = document.createelement (' tr ');
Thead.appendchild (TR);
var Th1 = document.createelement (' th ');
var Th2 = document.createelement (' th ');
var th3 = document.createelement (' th ');
Tr.appendchild (Th1);
Th1.appendchild (document.createTextNode (' name '));
Tr.appendchild (Th2);
Th2.appendchild (document.createTextNode (' age '));
Document.body.appendChild (table);
PS: Using the DOM to create a table is no more difficult, but a little cumbersome. Now we'll use the HTML DOM to get
and create this same table.
HTML dom, give these element tags a few properties and methods
Properties and Method Descriptions
Caption holds a reference to the <caption> element
Tbodies holds the Htmlcollection collection of <tbody> elements
TFoot holds a reference to the <tFoot> element
THead holds a reference to the <tHead> element
Rows holds the Htmlcollection collection of <tr> elements
Createthead () creates a <thead> element and returns a reference
Createtfoot () creates a <tfoot> element and returns a reference
Createcaption () creates a <caption> element and returns a reference
Deletethead () Delete <thead> element
Deletetfoot () Delete <tfoot> element
Deletecaption () Delete <caption> element
DeleteRow () deletes the specified row
InsertRow (POS) inserts a row into the rows collection at the specified location
Attributes and methods added by the <tbody> element
Property or method description
Rows holds the htmlcollection of the <tbody> elements
DeleteRow (POS) deletes a row at a specified location
InsertRow (POS) inserts a row into the rows collection at the specified location and returns a reference
Attributes and methods added by the <tr> element
Property or method description
Cells preserve the htmlcollection of cells in the <tr> element
Deletecell (POS) Delete a cell at the specified location
InsertCell (POS) inserts a cell into the cells collection at the specified location and returns a reference
PS: Because the table is more complex, the level is also many, before the use of the DOM learned before the only to get an element is very uncomfortable, so use htmldom
will be much clearer.
Use Htmldom to get table elements
var table = document.getelementsbytagname (' table ') [0];//gets the table reference
Get <caption> According to the previous DOM node method
alert (table.children[0],innerhtml);//Get caption Content
PS: The use of children[0] itself ignores the blank, if you use FirstChild or childnodes[0] need more code.
Press Htmldom to get the <caption> of the form
alert (Table.caption.innerHTML);//Get caption Content
Press Htmldom to get header footer <thead>, <tfoot>
alert (table.thead);//Get table header
alert (table.tfoot);//Get Footer
Press Htmldom to get the body of the table
alert (table.tbodies);//Gets the collection of the body of the table
PS: In a table <thead> and <tfoot> are unique, only one. And <tbody> is not the only one that can have multiple, which leads
The last returned <thead> and <tfoot> are element references, and <tbody> returns the collection of elements.
Press Htmldom to get the number of rows in the table
alert (table.rows.length);//Gets the collection of rows, the number
Get the number of rows in the body of a table
alert (table.tbodies[0].rows.length);//Gets the set of rows of the principal, the value
Gets the number of cells in the first row of the table body content (TR)
alert (table.tbodies[0].rows[0].cells.length);//Gets the number of cells in the first row
Gets the contents of the first cell of the first row of the table body content (TD)
alert (table.tbodies[0].rows[0].cells[0].innerhtml);
Delete title, header, footer, row, cell
Table.deletecaption ();//Delete title
Table.deletethead ();//Delete <thead>
table.tbodies[0].deleterow[0];//Delete <tr> row
Table.tbodies[0].rows[0].deletecell (0);//delete <td> a cell
Press Htmldom to create a table
var table = document.createelement (' table ');
Table.border = 1;
Table.width = 300;
Table.createcaption (). InnerHTML = ' personnel table ';
Table.createthead ();
Table.thead,insertrow (0);
var thead = Table.createthead ();
var tr = thead.innerrow (0);
var td = Tr.insertcell (0);
Td.appendchild (document.createTextNode (' data '));
var td2 = Tr.insertcell (1);
Td2.appendchild (document.createTextNode (' data '));
Document.body.appendChild (table);
PS: When creating a table <table>, <tbody>, <th> There are no specific methods that need to be created using document. You can also simulate
There are methods for writing specific functions, such as INSERTTH ().
Second, the Operation style
CSS as an assistant to (X) HTML can enhance the appearance of the page, but not every browser can support the latest CSS capabilities. CSS Capabilities
is closely related to the DOM level, so it is necessary to detect the level at which the current browser supports CSS capabilities.
DOM1 level to achieve the most basic document processing, DOM2 and DOM3 on this basis to add more interactive capabilities, here we mainly discuss
Css,dom2 adds CSS programmatic access and changes to CSS style information.
DOM-Consistent detection
Feature version number description
Core1.0, 2.0, 3.0 basic DOM used to represent the document node tree
XML1.0, 2.0, 3.0Core XML extensions, added support for CDATA, etc.
HTML1.0, 2.0XML thml extension, added support for HTML-specific elements
Views2.0 formatting of documents based on certain styles
StyleSheets2.0 associating a style to a document
CSS2.0 support for cascading style sheet level 1
CSS22.0 support for cascading style sheet level 2
EVENTS2.0 Regular DOM Events
UIEvents2.0 User Interface Events
MouseEvents2.0 events that are raised by the mouse (for example, click)
Events raised when the Mutationevents2.0dom tree changes
htmlevents2.0html4.01 Events
Range2.0 the user to manipulate a range of objects and methods in the DOM tree
Traversal2.0 How to traverse the DOM tree
synchronous loading and saving between the LS3.0 file and the DOM tree
synchronous loading and saving between the ls-async3.0 file and the DOM tree
Valuidation3.0 the method of modifying the DOM tree in the context of determining valid
Detects whether the browser supports DOM1-level CSS capabilities or DOM2-level CSS capabilities
Alert (' DOM1 level CSS capability: ' +document.implementation.hasfeature (' css ', ' 2.0 '));
Alert (' DOM1-level CSS capability: ' +document.implementation.hasfeature (' CSS2 ', ' 2.0 '));
PS: This detection scheme is not accurate in IE, IE6, hasfeature () method only returns true for HTML and version 1.0, all other functions
All return FALSE. However, IE still supports the most commonly used CSS2 modules.
1. Styles for accessing elements
Any HTML element tag will have a common attribute: style. It returns the Cssstyledeclaration object. Let's look at some of the most common
See the way in which the style of the line is accessed.
PS: Inline is the style attribute added in the label, the inline is the style that is written in the <style> tag, the link is through <link href>
The style that the label links to
CSS properties and JavaScript calls
CSS Properties JavaScript calls
Colorstyle.color
Font.sizestyle.fontSize
Float Non-IE:style.cssFloat
FloatIE:style.styleFloat
<div id= "box" style= "Color:red;background: #ccc; font-size:20px;float:right" > Test div</div>
var box = document.getElementById (' box ');//Get Box
Box.style.cssfloat.style;//cssstyledeclaration
Box.style.cssfloat.style.color;//red
box.style.cssfloat.style.fontsize;//20px
Box.style.cssFloat | | Box.style.stylefloat;//left, non-ie with cssfloat,ie stylefloat
PS: The above value can also be assigned value, the last assignment can be as follows:
typeof box.style.cssFloat! = ' undefined '? box.style.cssFloat = ' right ': box.style.styleFloat = ' right ';
The DOM2-level style specification defines properties and methods for the style
Properties and Method Descriptions
Csstext accessing or setting CSS code in a style
The number of LENGTHCSS properties
Cssrule Object for parentrulecss information
Getpropertycssvalue (name) returns the Cssvalue object that contains the value of the given property
Getpropertypriority (name) returns if!important is set, otherwise an empty string is returned
Item (index) returns the specified position of the CSS property name
Removeproperty (name) removes the specified attribute from the style
SetProperty (NAME,V,P) sets the appropriate value for the attribute and adds precedence
box.style.csstext;//Getting CSS Code
Box.style.length;//3,ie not supported
Box.style.removeProperty (' color ');//Remove a CSS property, ie does not support
Box.style.setProperty (' Color ', ' blue ');//Remove a CSS property, ie does not support
These properties and methods are supported by Ps:firefox, Safari, opera9+, and Chrome. IE only supports csstext, while Getpropertycssvalue ()
Methods only safari3+ and chrome support.
The Ps:style property can only get CSS styles within a row, and for the other two styles inline <style> and link <link> are not available.
Although a style can be used to get a single-valued CSS style, the style information for a composite value needs to be obtained by calculating the style. DOM2
Style, the getComputedStyle () method is provided under the Window object. Accepts two parameters, a style element that needs to be computed, and a second pseudo-class
(: hover), if there is no pseudo-class, fill null.
Ps:ie does not support this DOM2-level approach, but there is a similar property that can use the Currentstyle property.
<style>
#box {
color:red;
border:1px solid red;
Font-family: "Microsoft Jas Black";
font-size:20px;
}
</style>
var box = document.getElementById (' box ');
var style = Window.getcomputedstyle?window.getcomputedstyle (box,null): null | | Box.currentstyle;
alert (Style.color);
alert (Style.border);
alert (style.fontfamily);
alert (style.fontsize);
alert (box.style.fontFamily);//null
The Ps:border property is a comprehensive attribute, so it shows in Chrome that Firefox is empty and IE is undefined. The so-called comprehensive attribute
Is the shorthand for the XHTML course, so the DOM is best used for the best compatibility when it comes to CSS, such as:
Border-top-color or something like that.
PS: The calculation of the acquisition, not only can get the default style without setting, can also get inline, inline and link
Why do you get inline and link? Because no matter where you set up the CSS, it will eventually reside in the calculation style of my browser.
2. Manipulating Style Sheets
Using the Style property allows you to set the CSS style within the line, which is the most commonly used method by ID and class calls.
box.id = ' pox ';//changing the ID will bring about catastrophic problems.
Box.classname = ' red ';//Use the ClassName keyword to set the style
When adding clssname, we want to add more than one class to an element, there is no way, the latter will overwrite the previous one, so
You have to write a function.
Determine if a class exists
Returns true if there is no return false
Box.classname's string is ' AAA BBB '
Element.classname says ' aaa BBB '
Match is a method in a regular expression
If Element.classname ' AAA BBB ' inside has a regular string ' AAA '
Match is to find the string ' AAA BBB ' inside whether there is a/aaa/, if there is, put this character back
Element.classname no CCC, then return null
Convert to a Boolean value
Problem, with a AA can also return true
AA is not AAA, so this is not accurate
New RegExp (' (\\s|^) ' +cname+ ' (\\s|$) ') through this regular, we have strictly and precisely found the specified class
Check if class exists
function hasclass (element, CName) {
Return!! Element.className.match (New RegExp (' (\\s|^) ' +cname+ ' (\\s|$) ');
}
Add a Class
function AddClass (element,cname) {
if (!hasclass (Element,cname)) {
Element.classname + = "+ cName;
}
}
Remove a class
function Removeclass (element,cname) {
if (Hasclass (element, cName)) {
Element.classname = Element.className.replace (New RegExp (' (\\s|^) ' +cname+ ' (\\s|$) '), ');
}
}
Determine if this class exists
function Hasclass (element,classname) {
Return Element.className.match (New RegExp (' (\\s|^) ' +classname+ ' (\\s|$) ');
}
Add a class if it doesn't exist
function addclass (element, ClassName) {
if (!hasclass (Element,classname)) {
Element.classname + = "" +classname;
}
}
Delete a class if it exists
function removeclass (element, ClassName) {
if (Hasclass (element, className)) {
Element.classname = Element.className.replace (New RegExp (' (\\s|^) ' +classname+ ' (\\s|$) '), ');
}
}
Before we used the style property, we could only get and set the style within the line, if it was through inline <style> or a link <link> provided style
The rules are helpless, then we learn getComputedStyle and Currentstyle, which can only be obtained but not set.
The Cssstylesheet type represents the style sheet that is contained by the <link> element and the <style> element.
Document.implementation.hasFeature (' stylesheets ', ' 2.0 ');//whether the DOM2-level style sheet is supported
document.getElementsByTagName (' link ') [0];//htmllinkelement
document.getElementsByTagName (' style ') [0];//htmlstyleelement
The two elements themselves return the htmllinkelement and htmlstyleelement types, but the Cssstylesheet type is more generic
Get this type non ie use sheet attribute, ie use stylesheet;
<link href= "Css/css.css" type= "Text/css" ></link>
Css.css
#box {
}
var link = document.getelementsbytagname (' link ') [0];//get Link Tag object
var sheet = Link.sheet | | Link.stylesheet;//gets cssstylesheet that represents the linked CSS style sheet object
var sheet = document.stylesheets;//Gets the Stylesheetlist collection
Property or method description
Disabled gets and sets whether the style sheet is disabled
href if included through <link>, the style sheet is a URL, otherwise null
A collection of all media types supported by the media style sheet
Ownernode pointer to the node that owns the current style sheet
Parentstylesheet@import in case of import, get parent CSS Object
The value of the title property in Titleowernode
Type style sheet string
Cssrules style sheet contains a collection of style rules, ie does not support
In case of Ownerrule@import import, point to the rule that represents the import, IE does not support
DeleteRule (index) removes the rule from the specified position in the Cssrules collection, IE does not support
Insertrule (rule, index) Inserts a rule string into the Cssrules collection at the specified location, IE does not support
Sheet.disabled;//false, can be set to True
URL of Sheet.href;//css
Sheet.media;//medialist, Collection
sheet.media[0];//the value of the first media
sheet.title;//get the value of the title property
Sheet.cssrules;//cssrulelist, style sheet rule collection
alert (Sheet.cssrules[0].csstext); Get the text content of the first rule
alert (sheet.cssrules[0].selectortext);//The selector to get the first rule is #box
Sheet.deleterule (0);//delete the first style rule
Sheet.insertrule ("Body {background-color:red}", 0);//Add a style rule to the first position
PS: In addition to a few and IE does not support we ignore, there are three other ways to have ie corresponding:
sheet.rules;//instead of cssrules version of IE
Sheet.removerule (0);//replace DeleteRule's IE version
Sheet.addrule ("Body", "background-color:red", 0);//Replace the IE version of Insertrule
Get rules for cross-browser compatibility
var rules = Sheet.cssrules | | Sheet.rules;
Add the first rule across browser compatibility
function Insertrule (sheet, selectortext, csstext, position) {
if (sheet.insertrule) {
Sheet.insertrule (' Selectortext + ' {' +csstext+ '} ', position);
}else if (sheet.addrule) {
Sheet.addrule (Selectortext, csstext, position);
}
}
Remove the first rule from cross-browser compatibility
function DeleteRule (sheet, position) {
if (sheet.deleterule) {
Sheet.deleterule (position);
}else if (sheet.removerule) {
Sheet.removerule (position);
}
}
There is one way to get the Cssstylesheet type, in addition to the method you just made, through the StyleSheets property of the document.
Document.stylesheet;//stylesheetlist, Collection
Cssstylerule properties that can be used
Property Description
Csstext gets the text corresponding to the current entire rule, IE does not support
Parentrule@import imported return test Null,ie not supported
Parentstylesheet when the unspoken rules of the style sheet, IE does not support
Selectortext gets the selection text for the current rule
Style returns the Cssstyledeclaration object, which you can get and set style
Type represents a constant value for a rule, and for a style rule, a value of 1,ie does not support
rule.csstext;//style text for the current rule
rule.selectortext;//#box, selector for style
Rule.style.color;//red, get the specific style value
Ps:chrome The browser will be running locally, the rules will become null, as long as it is allowed to work on the server.
Summarize:
Three ways to manipulate CSS, in the first style line, readable writable, second inline, inline, and link, using getComputedStyle or
Currentstyle, readable non-writable, third cssrules or rules, inline and link readable writable.
19.DOM Operating Tables and styles