In section I, we introduce part of the Document Object Model (DOM), which provides an interface to support Script Programming for the document structure. Through Dom, HTML documents can be described as a series of nodes. Each node represents an object in the document, including all texts, identifiers, comments, and other data. Developers can use JavaScript to change these nodes to change the visual effect of the page in the browser. If you have read the previous article, you will know how to use the DOM method to create, insert, and remove elements from the page.
This article will discuss the Javascript node interface in depth, and examine some different methods used to change the visual attributes of elements or text nodes. You will first learn how to use the DOM element method to change the element attributes, and then learn how to use the DOM Level 2 (dom2) style standard interface to change the element's style attributes.
Obtains an element reference.
Before using the DOM interface to operate element nodes, you must first obtain a reference to the elements you want to operate on. The reference I mentioned here refers to a variable pointing to the correct object on the page. You may already be familiar with what most browsers supportdocument.images
,document.forms
, And other set variables. These sets are references to a group of internal page objects. If you need to reference an image element, and the attribute value of the name of the image element is "mgheader", you can use the set of image elements and capture the correct element by its name:
var img = document.images["imgHeader"];
However, these set variables only support a subset of page elements. For example, the script does not exist document.tables
Or document.paragraphs
Such a set can be used to obtain the reference of the corresponding category element.
Fortunately, the dom2 interface provides two methods to help us obtain any element reference (and this reference is closely related to the element itself-trust me, elements may change ). The two methods are:
document.getElementById(string id)
: Returns an element reference based on the specified ID.
document.getElementsByTagName(string tagName)
: Returns a set (array) of all elements with the specified identifier name ).
Therefore, if you want to obtain a reference to a table element whose ID attribute value is "tablemain", you can use the following JavaScript code:
var table = document.getElementById("tableMain");
Current variabletable
It should contain a reference pointing to the corresponding table.getElementById()
The method assumes that the page has a value that matches the value specified by the input parameter.Id attribute
Target element. If no matching element is foundgetElementById
Returns null.
Recognize ElementNAME
Attribute and itsID
Attributes are not the same. For exampleNAME
Attribute value, unless you have setID
Attribute Value. OtherwisegetElementById
Method. It is best to make the element unique at the same timeNAME
AndID
.
When you need to get references to all specific types of elements,getElementsByTagName()
Is very useful. This method returns a set containing references to all matching elements that can be found. For example, if you want to calculate the number of cells in a table on the page, you can use the following code:
var allTDs = document.getElementsByTagName("td");
alert("# of table cells: " + allTDs.length);
Please give it a try. click the button below to callgetElementsByTagName()
Method to calculate the number of cells in the current table on this page.
Calculate the number of TD
You can useitem()
Method. This method returns the reference of the specified index element. To reference the first and last table cells in the Set, use the following code:
var allTDs = document.getElementsByTagName("td");
var firstTD = allTDs.item(0).id;
var lastTD = allTDs.item(allTDs.length-1).id;
var str = "# of table cells: " + allTDs.length + "/n";
str += "First TD: " + firstTD + "/n";
str += "Last TD: " + lastTD;
alert(str);
Useitem()
Method, instead of directly referencing the position of the set, one advantage is that if the index you provide is invalid or the target element is not in the set,item()
The function returns a null value, while referencing a position subscript that does not exist in a set may produce an error message. In contrast, we usually prefer the former.
getElementsByTagName()
It is also a method of every element city, which means we can get a reference set of all elements within a specific element. The following code is called at the Element Level.getElementsByTagName()
To reference all the images in a table object:
var table = document.getElementById("myTable");
var imgs = table.getElementsByTagName("img");
Once an element is referenced, you can operate its attributes.
Read and set element attributes
The property of the element identifier is translated into the property of the object (the reference you created) by the browser. The DOM interface provides two methods for each element to read and set these attribute values:
getAttribute(string name)
: Returns the property value specified by the name parameter.
setAttribute(string name, string value)
: Add a new attribute with the specified name and value, or set an existing attribute to the specified value.
I often like to use a tool function to observe an element and look at the attributes and methods associated with it. Which will be seen laterinspect()
Function Pass getElementById()
The function gets an element reference and a warning box containing the element attribute list is displayed. The attribute and value strings are composedgetAttribute()
The value of each naming attribute obtained by the method is assembled.
function inspect(elm){
var str = "";
for (var i in elm){
str += i + ": " + elm.getAttribute(i) + "/n";
}
alert(str);
}
To useinspect()
When a function is used to evaluate a table element, you only need to pass the table element to the function:
table = document.getElementById("tableMain");
inspect(table);
Do you want to see how this function works? Click this button to view the following table.
One |
Two |
Three |
Four |
Five |
Six |
Seven |
Eight |
Nine |
Test table attributes
You can set a new element attribute throughsetAttribute()
Method. You only need to pass the attribute name and value you want to set to this function. Note that these two parameters must be strings, so even numeric values must be placed in quotation marks. If you want to reset the table width to 400 pixels, you can use the following code:
var table = document.getElementById("tableMain");
table.setAttribute("width","400");
The following example uses setAttribute()
AndchangeSize()
Method To set the width attribute of the table to different values.
function changeSize(px){
var table = document.getElementById("tableMain2");
table.setAttribute("width",px);
}
One |
Two |
Three |
Four |
Five |
Six |
Seven |
Eight |
Nine |
100px 200px 300px
If the attribute of the specified name does not exist in the element,setAttribute()
Method to create a new property. In factsetAttribute()
Compared with setting property values directly through JavaScript, this method has no essential benefit. The following two statements are essentially the same:
table.setAttribute("border","2");
table.border = 2;
To avoid setting unwanted new attributes, you can usehasAttribute()
To test whether a naming attribute exists.hasAttribute()
The method is based on whether the element has the corresponding attribute or returnstrue
Or return false
.
var table = document.getElementById("tableMain");
if (table.hasAttribute("border")){
table.setAttribute("border","2");
} else {
alert("Table has no border");
}
It should be noted that,hasAttribute()
This method is only supported on the Netscape 6/Mozilla Browser. ie5 does not support this method when writing this article.
Operating element style
So far, we will only discuss how to operate on the attributes of elements. In general, an element uses CSS to define a specific style and format. Similar methods are used to change the CSS attribute of an element, but there is a slight difference.
The DOM specification provides another interface called the DOM Level 2 style interface (DOM Level 2 style), which is used to manipulate the CSS attributes of elements. Each CSS rule of an element can be expressed by an attribute of an element style object.
Style is an object, so we can useInspect () is similar
To evaluate its attributes. The followinginspectStyle()
Before examining the style attribute values, the function first checks whether the target element has a style object. As we discussed in this article about style modification, there is a defect in the current official versions of Netscape 6 and Mozilla, so that in these browsers, the CSS rules in the embedded style form cannot be correctly reflected in the style object. Therefore, to make this demo correct, all elements passSTYLE
The attribute defines CSS in its own identifier.
function inspectStyle(elm){
if (elm.style){
var str = "";
for (var i in elm.style){
str += i + ": " + elm.style[i] + "/n";
}
alert(str);
}
}
var header = document.getElementById("h2");
inspectStyle(header);
Click the buttons below to view the style attribute of the H2 element below. Note: Some Mac OS X ie 5.1 preview versions may encounter problems when running the following script.
The title is here
CSS of title
You will notice that many style attributes are empty because they are not defined as other values. You can set style attributes directly. If you want to read and set the background color of the HTML page (or, specifically, the background color of the Body element), see the following code:
var doc = document.getElementsByTagName("body").item(0);
var color = doc.style.backgroundColor;
alert ("Background color is: " + color);
doc.style.backgroundColor = "#0000ff";
The CSS attribute of the Operation element is the key to the DHTML function. For example, you can use JavaScript to change the left and background-color CSS attributes of a table to change its color and position on the page. Try the following buttons:
One |
Two |
Three |
Four |
Five |
Six |
Seven |
Eight |
Nine |
Change location:
100px to the right 100px left
Change color:
The following is the Javascript that completes the above functions. In all these cases, the table ID "tablemain" is passed to the getelementbyid () function to obtain the reference of table elements. The new CSS property values are directly assigned to style objects.
<span class="sourcecode">
<script language="JavaScript" type="text/javascript">
function tableRight(){
var table = document.getElementById("tableMain3");
table.style.left = "100px";
}
function tableLeft(){
var table = document.getElementById("tableMain3");
table.style.left = "0px";
}
function changeTColor(col){
var table = document.getElementById("tableMain3");
table.style.backgroundColor = col;
}
To obtain style attributes that support Script Programming, we first obtain the original style rules from the CSS declaration, and convert the first letter followed by each hyphen into uppercase letters, remove all the hyphens. The following table contains some instances:
CSS attributes |
Equivalent Definition in Javascript |
Background-color |
Style. backgroundcolor |
Font-size |
Style. fontsize |
Left |
Style. Left |
Border-top-Width |
Style. bordertopwidth |
Starting from here
This is a brief introduction to the Document Object Model. We are exposed to some exciting Dom functions, including creating dynamic elements and setting element attributes and CSS attributes through JavaScript. More functions of the DOM interface are not described in these articles. I encourage you to go to the W3C website to check related specifications, especially the ecmascript Association page, these pages describe the DOM Level 2 core and style scripting interface (DOM Level 2 core and style scripting Interface) in more detail ). Check your browser documentation to see what Dom features it supports.
Now you may want to jump to some articles by Dom-based Internet developers, such as navigator 6 DHTML and modification style, both articles discuss the complexity of the process of changing the document display results through Script Programming.
More information
- Process dynamic content with a DOM-2, part I.