JavaScript DOM (2)

Source: Internet
Author: User

JavaScript DOM (2)
HTML element features and DOM attributes

Attribute and DOM object property in HTML tags are two confusing concepts. In fact, they are very important for understanding the Document Object Model. We usually translate the attribute of the HTML tag into "feature" and the property of the DOM object into "attribute ".

The Document Object Model (DOM) is an API for HTML and XML documents. DOM depicts a hierarchical node tree that allows us to add, remove, and modify a part of a page through DOM.

In fact, there are two concepts: HTML pages and DOM object models.

For example:

 
... 

The above is an HTML element. The "id", "class", and "title" are all attributes of this element ). What should we do if we want to access and delete these div features through JS? In JS, we can use DOM to get reference of corresponding elements:

var div1 = document.getElementById("div1");

Note that div1 is a reference to a JS object. This object contains attributes such as "id", "className", and "title ). They correspond to the "id", "class", and "title" Features of div elements in HTML. Generally, their names are the same. For example, "id" corresponds to "id", and "title" corresponds to "title. But here, because class is a reserved word in JS, "calssName" corresponds to the "calss" feature of the div element.

You can use the corresponding attribute in the div1 object or the getAttribute, setAttribute, and removeAttitude methods to access the attribute values in the HTML element. However, it should be noted that the element features and DOM object attributes are two different concepts.

Each Element in HTML corresponds to an HTMLXXXElement interface in DOM. This interface inherits from HTMLElement, while the HTMLElement interface directly inherits from Element, and the Element interface inherits from Node.

Element Node

Element nodes are commonly used in Web programming. The content is divided into the following parts:

How to obtain the features of HTML elements using Element tag names: obtaining the names of created Element tags for attributes attribute elements of Element-type nodes

Among the 12 Node types defined in the Node type, the Element type belongs to Node. ELEMENT_NODE, corresponding to the value 1. The basic features are as follows:

NodeType value is 1 nodeName value is element label name nodeValue value is null

The tag name of the element can be obtained directly through the nodeName attribute. For example:

 
... 
... var div1 = document.getElementById("div1"); var tag1 = div1.nodeName;  

In addition, you can also obtain the tagName attribute. The returned values are the same:

var tag2 = div1.tagName;  // tag1 == tag2

Note that in HTML, the tag name of an element is always uppercase:

alert(tag1);  // DIV

The signature winning in XML will be consistent with the source code. Therefore, to ensure code compatibility in HTML and XML, we recommend that you perform a unified case-sensitivity conversion before operating the Tag Name:

if(element.tagName.toLowerCase() == "div") { ... }
Operation Method of HTML element features 1 access element features through DOM attributes 2 access element features through getAttribute method 3 set element features through setAttribute Method 4 Delete element features through removeAttribute 1 access elements through DOM attributes features

In DOM, all HTML elements correspond to an HTMLElement interface or its subinterfaces. As an example, we will list the mappings between several common elements:

HTML Element DOM interface
H1 ~ H6 HTMLHeadingElement
FORM HTMLFormElement
DIV HTMLDivElement
CITE HTMLElement
P HTMLParagraphElement

The DOM object corresponding to the HTML element contains the attributes corresponding to the HTML element features. We use the div element as an example to list several basic features:

DIV element features DOM attributes
Id Id
Title Title
Dir Dior
Class ClassName
... ...

Again, because class is a reserved word in JS, the attribute corresponding to the class feature in the HTML element is named className.

You can use the DOM attribute to directly access and modify the corresponding HTML features:

 
... 
... var div1 = document.getElementById("div1"); div1.di = 'newdiv'; div.className = "newbd"; div.title = "newTitle";  

All features of all HTML elements can be accessed through the attributes of the DOM element. There is only one exception, custom features. Custom features are not added to DOM objects as attributes:

 
... 
... var div1 = document.getElementById("div1"); alert(div1.data-myAttr); //VM226:1 Uncaught ReferenceError: myAttr is not defined(…)  

However, custom attributes can be obtained through the getAttribute method, which will be discussed later.

2. Use the getAttribute method to access element features

In addition to accessing the features of elements through attributes, DOM objects also provide the getAttribute Method for us to obtain feature values. GetAttribute receives one parameter, that is, the name of the feature to be accessed. If the feature does not exist, null is returned:

 
... 
... var div1 = document.getElementById("div1"); alert(div1.getAttribute("id")); //div1 alert(div1.getAttribute("class")); //bd alert(div1.getAttribute("title")); //Body text  

Note that when the getAttribute method is used, when the special name of the element is used, we will pass in the corresponding parameter, including the "class" with exceptions in attribute access ". In addition, the getAttribute method can also access our custom features:

 
... 
... var div1 = document.getElementById("div1"); alert(div1.data-myAttr); //easy  

Note: According to HTML5 specifications, the custom features should be prefixed with data for verification.

3. Set element features using the setAttribute Method

SetAttribute can be used to set feature values for elements. This method receives two parameters. The first parameter is the name of the feature to be set, and the second parameter is the value to be set. Note: If the feature to be set does not exist, this method will create and set the corresponding value. Easy to use:

 
... 
... Var div1 = document. getElementById ("div1"); div1.setAttribute ("id", "newvid"); div1.setAttribute ("class", "newbd"); div1.setAttribute ("title", "newTitle "); div1.setAttribute ("dir", "rtl"); // set new features! 

In addition, the setAttribute method can set custom features:

div1.setAttribute("data-myAttr", "easy");     alert(div1.getAttribute("data-myAttr"));  //easy

If you directly use the property method to add a custom property, this property will not become an element feature, although it will exist in the DOM attribute:

div1.data-myAttr = easy;     alert(div1.getAttribute("data-myAttr"));  //nullalert(div1.data-myAttr);  //easy

Actuallydiv1.data-myAttr = easyIt is equivalent to adding an attribute to a common JavaScript Object.

In addition, although getarrtivity and setAttribute are case-insensitive, I think this is not a good habit. We recommend that you maintain consistency when writing.

4. Delete element features using the removeAttribute Method

This method is used to completely delete the features of an element. The method receives a parameter, that is, the name of the element feature to be deleted.

div1.removeAttrubute("title");
Attributes of Element nodes

Every feature of the HTML element is stored in the NamedNodeMap object pointed to by the attributes attribute of the Node object. Do you still remember the 12 Node types defined in Node? In NamedNodeMap, each HTML element is saved as a Node of the Node. ATTRIBUTE_NODE type (corresponding to value 2. The following code is used as an example:

    
  • Apple
  • Watermelon
  • Pear
  • Orange

We get the NamedNodeMap pointed to by the attributes attribute of the ul element, which contains two nodes:

0: id1: class

They are all Node. ATTRIBUTE_NODE nodes:

Element Creation

In DOM, we can use the document. createElement () method to create a new element. This method receives a parameter, that is, the tag name of the new element to be created. Note that after calling this method to create an element, the new element is not added to the document tree, we can call the appendChild, insertBefore, or replaceChild methods to add the new element to the document tree to render the element in the browser. For example, the following HTML code:

  
Nice Fruit

Eat them usually.

  • Apple
  • Watermelon
  • Pear
  • Orange

Run the following JS Code:

  var myh2 = document.createElement("h2");  var mytext = document.createTextNode("Nice Candy");  myh2.appendChild(mytext);  document.body.appendChild(myh2);

The "Nice Candy" h2 title is added to the HTML page.

In addition, when a new element is created using the document. createElement () method, the ownerDocument attribute of the element is also specified as the current document.

Text Node

The Element type nodes described above are only one of the 12 types. In this document, the Element type node usually provides a structure that does not contain too much content. Most of the content is provided by text. Text nodes are always contained in element nodes, but not all element nodes contain text nodes.

Text node basic features create an operation node text method for text nodes Basic Features

The basic information about nodes can be provided through its nodeType, nodeName, and nodeValue attributes. In a text node, the value of nodeType is 3, nodeName is "# text", and nodeValue is the specific text contained in it.

We can use the nodeValue attribute to access the specific text content of a text node. For the sake of intuition, we can also use the data attribute to access the specific text content of a text node. The two contain the same value. Any modification to one of the attributes is reflected in another attribute.

The length attribute of a text node contains the number of node characters. Similarly, we can usemyText.nodeValue.lengthOrmyText.data.lengthTo access this property. The two Save the same value.

The following code is used as an example:

 

Eat them usually.

 

Create a text node

You can use the createTextNode method to create a text node. This method accepts a parameter to indicate the text content of the node:

document.createTextNode("Hello World! 
  
   ");
  

Note the following points in the preceding example:

1. The content of a text node is plain text and cannot contain HTML code. The character string of the text node is automatically HTML encoded. The quotation marks are escaped. The text in the preceding example is escaped as follows:
"Hello World! <This is a nice world!>"
2. When a Text node is created, its ownerDocument attribute is automatically specified as the current document. 3. The newly created Text node is the same as the createElement method, it must be added to the DOM tree using appendChild, insertBefore, replaceChild, and other methods. 4. Generally, each element that can contain a text node can contain only one text node, the node must contain content. If we create multiple file subnodes for an element node, these text nodes will be displayed when they are displayed, without spaces in the middle. They are mutually sibling nodes. However, there are adjacent compatriot text nodes in the DOM document, which can easily lead to confusion. We can use the normalize () method to merge adjacent text nodes.

The above code is also used as an example:

  
Nice Fruit

Eat them usually.

  • Apple
  • Watermelon
  • Pear
  • Orange

How to operate node text

The usage of these methods is similar to that of string operations.

AppendData (text): Add text to the end of the text; deleteData (offset, count): delete count characters from offset; insertData (offset, text ): insert text at offset; replaceData (offset, count, text): replace the count characters starting from offset with text; splitText (offset): Split text from offset, returns the new node from offset to the end of the text;

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.