JavaScript DOM (ii)

Source: Internet
Author: User
Tags pear tag name tagname

    • HTML element attributes and Dom properties
    • Element type node
    • Text Type node
HTML element attributes and Dom properties

The property of the attribute and Dom objects in the HTML tag is two more confusing concepts, in fact, both of which are important for understanding the Document Object model. Usually we translate the attribute of the HTML tag into "attributes" and translate the property of the DOM object into "Properties".

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

In fact, it contains 2 concepts, one is an HTML page and the other is the DOM object model.

Let's say for example:

<div id="div1" class="bd" title="Body text">...</div>

The above is an HTML element. The "id", "Class", and "title" are all attributes of the element (attribute). What do we want to be able to access and snip these features of the div with JS? In JS we can get a reference to the corresponding element through the DOM:

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

Note that the DIV1 here is a reference to a JS object. The object contains attributes such as "id", "className", "title", and so on. They correspond to the "id", "Class", and "title" attributes of the div element in HTML. Typically, their names are the same. For example, "id" and "id" correspond, "title" and "title" correspond. But here, because class is a reserved word in JS, "Calssname" corresponds to the "CALSS" attribute of the DIV element.

We can access the attribute values in the Div1 HTML element by using the corresponding attribute in the object or the GetAttribute, SetAttribute, and Removeattitude methods. However, it is important to note that element attributes and Dom object properties are two different concepts.

Each element in the HTML corresponds to a htmlxxxelement interface in the DOM, which inherits from HtmlElement, and the HtmlElement interface inherits directly from element, and the element interface inherits from node.

Element type node

Element type nodes are very common in web programming. More content, divided into the following sections:

    • Get the element tag name
    • How to manipulate HTML element attributes
    • The Attributes property of the element type node
    • Creation of elements
Get the element tag name

Of the 12 types of nodes defined in the node type, the ELEMENT type is node.element_node, corresponding to the value 1. The basic features are as follows:

    • NodeType value is 1
    • NodeName value for element label signature
    • NodeValue value is null

We want to get the tag name of the element can be obtained directly through the NodeName property, for example:

<div id="div1" class="bd" title="Body text">...</div>...var div1 = document.getElementById("div1");var tag1 = div1.nodeName;

Alternatively, it can be obtained from the TagName property, and the return value is exactly the same:

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

The only thing to note is that in HTML, the tag name of an element is always uppercase:

alert(tag1);  // DIV

and the signature in XML is consistent with the source code, so in order to ensure the code's compatibility in HTML and XML, we'd better do a uniform case translation before manipulating the tag name:

if(element.tagName.toLowerCase() == "div") { ... }
How to manipulate HTML element attributes
    • 1 accessing element attributes through DOM properties
    • 2 accessing element attributes through the GetAttribute method
    • 3 setting element properties by using the SetAttribute method
    • 4 removing element attributes by RemoveAttribute method
1 accessing element attributes through DOM properties

In the DOM, all HTML elements correspond to a HtmlElement interface or its sub-interfaces. As an example, we enumerate the corresponding relationships of several commonly used elements:

HTML Elements DOM Interface
H1~h6 Htmlheadingelement
FORM Htmlformelement
Div Htmldivelement
CITE HtmlElement
P Htmlparagraphelement

In the DOM object corresponding to the HTML element, which contains attributes corresponding to the attributes of the HTML element, we use the DIV element as an example to list several basic features:

Div element Attributes Dom Properties
Id Id
Title Title
Dir Dior
Class ClassName
... ...

Again, since class is a reserved word in JS, the attribute corresponding to the class attribute in the HTML element is named ClassName.

We can modify the corresponding HTML attributes directly through the DOM property:

<div id="div1" class="bd" title="Body text">...</div>...var div1 = document.getElementById("div1");div1.di = ‘newdiv‘;div.className = "newbd";div.title = "newTitle";

All the attributes of all HTML elements can be accessed through the properties of the DOM element itself. There is only one exception to the custom attribute. Custom attributes are not added to the DOM object as attributes:

<div id="div1" class="bd" data-myAttr = "easy">...</div>...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 said later.

2 accessing element attributes through the GetAttribute method

In addition to the attributes that can be accessed through properties, the DOM object also provides us with the GetAttribute method to get the attribute value. GetAttribute receives 1 parameters, that is, the name of the attribute to be accessed, and returns null if the attribute does not exist:

<div id="div1" class="bd" title="Body text">...</div>...var div1 = document.getElementById("div1");alert(div1.getAttribute("id"));  //div1alert(div1.getAttribute("class"));  //bdalert(div1.getAttribute("title"));  //Body text

It is emphasized that when using the GetAttribute method, the name of the attribute in the element, we pass in the corresponding parameter, including the exception of "class" in the property access. In addition, the GetAttribute method can access our custom features:

<div id="div1" class="bd" data-myAttr = "easy">...</div>...var div1 = document.getElementById("div1");alert(div1.data-myAttr);  //easy

Note that, according to the HTML5 specification, custom attributes should be prefixed with data-for validation.

3 setting element properties by using the SetAttribute method

SetAttribute can be used to set attribute values for an element. The method receives 2 parameters, the first is the attribute name to be set, and the second is the value to be set. Note that if the attribute to be set does not exist, the method creates and sets the corresponding value. The usage is simple:

<div id="div1" class="bd" title="Body text">...</div>...var div1 = document.getElementById("div1");div1.setAttribute("id", "newvid");div1.setAttribute("class", "newbd");div1.setAttribute("title", "newTitle");div1.setAttribute("dir", "rtl");  //设置新特性!

In addition, the SetAttribute method can set the custom attributes:

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

If you add a custom attribute by using the property's method directly, the property is not an attribute of the element, although it exists in the properties of the DOM:

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

It's actually div1.data-myAttr = easy just the equivalent of adding a property to an ordinary JavaScript object.

In addition, although Getarrtibute and setattribute are not case-sensitive, but I think this is not a good habit, we write in the time, the best parties to maintain the same.

4 removing element attributes by RemoveAttribute method

This method is used to completely remove the attributes of an element, and the method receives a parameter that is the name of the element attribute to be deleted.

div1.removeAttrubute("title");
The Attributes property of the element type node

Each attribute of an HTML element is saved in the NamedNodeMap object pointed to by the node object Attributes property. Remember the 12 node types defined in node? You can refer to the JavaScript DOM (a). In NamedNodeMap, each HTML element attribute is saved as a node of type Node.attribute_node (corresponding to the value 2). Let's take the following code as an example:

    <ul id="List1">      <li class="Fruit" name="Li1">Apple</li>      <li class="Fruit" name="Li2">Watermelon</li>      <li class="Fruit" name="Li3">Pear</li>      <li class="Fruit" name="Li4">Orange</li>    </ul>

We get the attributes attribute of the UL element to point to the NamedNodeMap, which contains 2 nodes:

0: id1: class

They are all Node.attribute_node type nodes:

Creation of elements

In the DOM, we can use the Document.createelement () method to create a new element. The method receives a parameter that is the label name of the new element to be created. It is important to note that the new element is not added to the document tree after calling the method to create the element, and we can call the appendchild described in the JavaScript DOM (a), The InsertBefore or ReplaceChild method adds the newly created element to the document tree to render the element in the browser. For example, the following HTML code:

  <body>    <h2>Nice Fruit</H2>    <p Title="A List of fruit">Eat them usually.</P>    <ul id="List1" class="ul">      <li class="Fruit" name="Li1">Apple</li>      <li class="Fruit" name="Li2">Watermelon</li>      <li class="Fruit" name="Li3">Pear</li>      <li class="Fruit" name="Li4">Orange</li>    </ul>  </body>   

Execute the following JS code:

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

A "nice Candy" H2 title is added to the HTML page.

It is also stated that, while creating a new element through the Document.createelement () method, the Ownerdocument property of the element is also specified as the current document.

Text Type node

The element type node described above is only one of 12 types. In a document, an element type node typically provides a structure that does not contain too much content. Content is provided by text at a large number of times. Text nodes are always contained within an element node, but not all element nodes contain text nodes.

    • Text Node basic features
    • Creation of text nodes
    • Methods for manipulating node text
Text Node basic features

The basic information about a node can be provided through its nodetype, NodeName, and NodeValue properties. In a text node, the NodeType value is 3,nodename "#text", which is the specific text that is contained in NodeValue.

We can access the specific contents of the text through the NodeValue property, and for the sake of intuition, we can also access the text node's specific text content through the Data property. Both contain the same value. Modifications to any of these properties are reflected on the corresponding other property.

The length property of the text node holds the number of node characters. Similarly, we can either myText.nodeValue.length myText.data.length access the property or save the same value.

The following code is an example:

<p title="A list of fruit" id="p1">Eat them usually.</p>

Creation of text nodes

Create a text node you can use the createTextNode method, which takes a parameter that represents the text content of the creation node:

document.createTextNode("Hello World! <This is a nice world!>");

In the above example, the following points need to be noted:

    • 1, the content of the text node is plain text content, cannot contain HTML code. The text node's string is automatically HTML-encoded. The greater than sign, the less-than sign, and the quotation marks are escaped. The text content of the above example is escaped as follows:
"Hello World! &lt;This is a nice world!&gt;"
    • 2, the text node is created at the same time, its Ownerdocument property is automatically designated as the current document;
    • 3, the same createelement method, the newly created text node, need to be appendchild, InsertBefore, ReplaceChild and other methods added to the DOM tree will be displayed by the browser;
    • 4. Typically, each element that can contain a text node contains at most 1 text nodes, and the node must have content present. If we create more than one text child node for an element node, the text nodes will be displayed in the display, with no spaces in the middle, and they are sibling nodes to each other. But the presence of neighboring sibling text nodes in DOM documents can easily lead to confusion, and we could merge adjacent text nodes with the normalize () method.

Also take the above code as an example:

  <body>    <h2>Nice Fruit</H2>    <p Title="A List of fruit" id="P1">Eat them usually.</P>    <ul id="List1" class="ul">      <li class="Fruit" name="Li1">Apple</li>      <li class="Fruit" name="Li2">Watermelon</li>      <li class="Fruit" name="Li3">Pear</li>      <li class="Fruit" name="Li4">Orange</li>    </ul>  </body>   

Methods for manipulating node text

The use of these methods is similar to string manipulation, and this memo is no longer an example.

    • AppendData (text): Adds text to the end of the text;
    • DeleteData (offset, count): Deletes count characters starting at offset;
    • InsertData (offset, text): Inserts text at offset;
    • ReplaceData (offset, count, text): Use text to replace the count character from offset;
    • Splittext (offset): Splits the text from the offset position, returning the new node offset to the end of the text;

JavaScript DOM (ii)

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.