Element type

After the Document type, the Element type is the most commonly used type in Web programming. The Element type is used to represent XML or HTML elements and provides access to the Element’s tag name, child nodes, and attributes. The Element node has the following characteristics:

  • nodeTypeIs 1;
  • nodeNameIs the tag name of the element;
  • nodeValueThe value ofnull;
  • parentNodeMay beDocumentElement;
  • The child nodes may beElement,Text,Comment,ProcessingInstruction,CDATASectionEntityReference.

To access the tagName of an element, you can use either the nodeName or tagName attribute; Both attributes return the same value (the latter is used mainly for clarity). Take the following elements:


     
Copy the code

The element and its tag name can be obtained as follows:

var div = document.getElementById("myDiv");
console.log(div.tagName); // "DIV"
console.log(div.tagName === div.nodeName); // trueCopy the code

The element tag name is div, and it has an ID with a value of “myDiv”. However, div. TagName actually prints “div” instead of “div”. In HTML, tag names are always in all uppercase; In XML (and sometimes XHTML), the tag name is always the same as in the source code. If you are not sure whether your script will be executed in AN HTML or XML document, it is best to convert the tag name to the same case before comparing, as shown in the following example:

// This is not the case. If (element. TagName = = "div") certain operations} {/ / performed here / / best (applicable to any document) if (element. TagName. ToLowerCase () = = "div") {/ /} to perform certain actions in thisCopy the code

The HTML element

All HTML elements are represented by the HTMLElement type, not directly through this type but also through its subtypes. The HTMLElement type inherits directly from Element and adds some attributes. The attributes added correspond to the following standard properties that are present in each HTML element.

  • id, the unique identifier of the element in the document.
  • titleAdditional descriptive information about the element, usually displayed through a tooltip.
  • langElement content language code, rarely used.
  • dir, the direction of the language, and the value is"ltr"(left-to-right, from left to right) or"rtl"(right-to-left, from right to left) and rarely used.
  • className, and the elementclassProperty corresponds to the CSS class specified for the element. This property is not named asclassBecause,classIs a JavaScript reserved word.

These attributes can be used to obtain or modify the corresponding property values. Take the following HTML elements for example:


     
Copy the code

All information specified in the element can be obtained with JavaScript code:

var div = document.getElementById("myDiv");
console.log(div.id);         // "myDiv""
console.log(div.className);  // "bd"
console.log(div.title);      // "Body text"
console.log(div.lang);       // "en"
console.log(div.dir);        // "ltr"Copy the code

Of course, you can also modify each property by assigning a new value to each property as follows:

div.id = "someOtherId";
div.className = "ft";
div.title = "Some other text";
div.lang = "fr";
div.dir ="rtl";Copy the code

Not all property changes are visually visible on the page. Changes to id or lang are transparently invisible to the user (assuming there is no CSS style based on their value), while changes to title are only visible when the mouse moves over the element. Changes to dir will affect the left and right alignment of text on the page the moment the property is overridden. When you modify className, if the new class is associated with a different CSS style than the previous one, the new style is immediately applied.

Obtain features

Each element has one or more features whose purpose is to give additional information about the element or its contents. There are three DOM methods for manipulating features: getAttribute(), setAttribute(), and removeAttribute(). These three methods can be used for any feature, including those defined as HTMLElement type attributes. Consider the following example:

var div = document.getElementById("myDiv");
console.log(div.getAttribute("id"));     // "myDiv"
console.log(div.getAttribute("class"));  // "bd"
console.log(div.getAttribute("title"));  // "Body text"
console.log(div.getAttribute("lang"));   // "en"
console.log(div.getAttribute("dir"));    // "ltr"Copy the code

Notice that the attribute name passed to getAttribute() is the same as the actual attribute name. So to get the class property value, you should pass in “class” instead of “className”, which is used only when the property is accessed through object properties. GetAttribute () returns NULL if the attribute with the given name does not exist.

The getAttribute() method can also get the value of a custom attribute (that is, a feature not found in the standard HTML language), as in the following element:


     
Copy the code

This element contains a custom attribute called my_special_attribute, which has the value “Hello!” . This value can be obtained just like any other feature, as shown below:

var value = div.getAttribute("my_special_attribute");Copy the code

However, feature names are case insensitive, meaning that “ID” and “ID” represent the same feature. Also note that according to the HTML5 specification, custom features should be prefixed with data- for validation purposes.

All attributes of any element are also accessible through attributes of the DOM element itself. Of course, HTMLElement also has five attributes that correspond to the corresponding feature. However, only recognized (non-custom) features are added to DOM objects as attributes. Take the following elements:


     
Copy the code

Because ID and align are recognized features of div in HTML, corresponding attributes will also exist in the DOM object for that element. However, the custom my_special_attribute feature doesn’t exist in Safari, Opera, Chrome, or Firefox; But IE also creates attributes for custom features, as shown in the following example:

console.log(div.id); // "myDiv" console.log(div.my_special_attribute); // undefined (except IE) console.log(div.align); // "left"Copy the code

There are two special classes of attributes that have corresponding attribute names but whose values are not the same as those returned by getAttribute(). The first type of feature is style, which is used to style elements with CSS. When accessed through getAttribute(), the returned style property value contains CSS text, while accessing it through the property returns an object. Because the style attribute is used to programmatically access element styles, it is not directly mapped to the style attribute.

The second distinctive feature is an event handler like onclick. When used on elements, the onClick feature contains JavaScript code that, if accessed through getAttribute(), returns a string of the corresponding code. When the onclick property is accessed, a JavaScript function is returned (or null if the property is not specified in the element). This is because onclick and other event handler properties should be assigned function values themselves.

Because of these differences, when manipulating the DOM programmatically through JavaScript, developers often do not use getAttribute(), but only the attributes of the object. The getAttribute() method is used only if a custom attribute value is obtained.

Set the properties

The corresponding method to getAttribute() is setAttribute(), which takes two parameters: the name of the attribute to be set and the value. If the attribute already exists, setAttribute() replaces the existing value with the specified value; If the attribute does not exist, setAttribute() creates the attribute and sets the corresponding value. Consider the following example:

div.setAttribute("id", "someOtherId");
div.setAttribute("class", "ft");
div.setAttribute("title", "Some other text");
div.setAttribute("lang","fr");
div.setAttribute("dir", "rtl");Copy the code

The setAttribute() method allows you to manipulate both HTML attributes and custom attributes. Property names set in this way are uniformly converted to lowercase, meaning that “ID” eventually becomes “ID”.

Because all properties are properties, assigning a property directly sets the value of the property, as shown below.

div.id = "someOtherId";
div.align = "left";Copy the code

However, adding a custom attribute to a DOM element like the following does not automatically become a feature of the element.

div.mycolor = "red"; console.log(div.mycolor); // "red" console.log(div.getAttribute("mycolor")); // null (IE excepted)Copy the code

This example adds a property called myColor and sets its value to “red”. In most browsers, this attribute does not automatically become a property of the element, so trying to get a value of the same property using getAttribute() returns NULL. However, custom attributes are treated as attributes of elements in IE and vice versa.

The final method to cover is removeAttribute(), which is used to completely remove the attributes of an element. Calling this method not only clears the attribute’s value, but also removes the attribute completely from the element, as shown below:

div.removeAttribute("class");Copy the code

This method is not commonly used, but when serializing DOM elements, you can use it to specify exactly what features to include.

Create the element

New elements can be created using the document.createElement() method. This method takes only one parameter, the label name of the element to be created. This tag name is case insensitive in HTML documents. For example, you can create a div element with the following code.

var div = document.createElement("div");Copy the code

When you create a new element using the createElement() method, you also set the ownerDocuemnt property for the new element. At this point, you can also manipulate the element’s properties, add more child nodes to it, and do other things. Consider the following example.

div.id = "myNewDiv";
div.className = "box";Copy the code

Setting these features on new elements just gives them the information they need. Because the new elements have not yet been added to the document tree, setting these features does not affect the browser’s display. To add a new element to the document tree, use the appendChild(), insertBefore(), or replaceChild() methods. The following code adds the newly created element to the document’s element.

document.body.appendChild(div);Copy the code

Once an element is added to the document tree, the browser renders it immediately. Any subsequent changes to this element are reflected in the browser in real time.

Element child node

An element can have any number of children and descendants because an element can be a child of another element. The childNodes attribute of the element contains all of its childNodes, which can be elements, text nodes, comments, or processing instructions. There are significant differences in how browsers view these nodes, as shown in the following code.


     
  • Item 1
  • Item 2
  • Item 3
    Copy the code
  • If IE8 parses this code, then

      • 
              
        • Item 1
        • Item 2
        • Item 3Copy the code
        • So for this code,

            childNodes nodeTpye

            for (var i=0, len=element.childNodes.length; i < len; I ++){if (element.childNodes[I].nodeType == 1){// Perform some operations}}Copy the code

            This example loops through each child node of a particular element, and then does something only if the nodeType of the child node is equal to 1, indicating that it is an element node.

            What if you want to get a child or descendant node from a particular tag name? In fact, the element also supports the getElementsByTagName() method. When this method is called through an element, it is the same as when it is called through a document, except that the starting point of the search is the current element, so only descendants of the current element are returned. For example, if you want to get the front

            • var ul = document.getElementById("myList");
              var items = ul.getElementsByTagName("li");Copy the code

              And notice, here

              • The Text type

                Text nodes are represented by the Text type and contain plain Text content that can be interpreted literally. Plain text can contain escaped HTML characters, but not HTML code. The Text node has the following characteristics:

                • nodeTypeIs 3;
                • nodeNameThe value of"#text";
                • nodeValueIs the text contained by the node;
                • parentNodeIs aElement;
                • No child nodes are supported.

                The Text contained in the Text node can be accessed through either the nodeValue attribute or the data attribute, which contain the same value. Changes to nodeValue are also reflected through data and vice versa. You can manipulate text in a node using the following methods.

                • appendData(*text*)Will:*text*Add to the end of the node.
                • deleteData(*offset*, *count*)From:*offset*Starts deletion at the specified location*count*A character.
                • insertData(*offset, text*)In:*offset*Insert at the specified position*text*.
                • replaceData(*offset, count, text*):*text*Replace from*offset*Start at the specified location*offset*+*count*Up to the point of text.
                • splitText(*offset*)From:*offset*The specified location divides the current text node into two text nodes.
                • substringData(*offset, count*)Extraction from:*offset*Start at the specified location*offset+count*String at point.

                In addition to these methods, the text node also has a length attribute, which holds the number of characters in the node. Also, the same values are stored in nodevalue. length and data.length.

                By default, each element that can contain content can have at most one text node, and it must actually have content. Let’s do a couple of examples.

                
                
                      
                Hello World!Copy the code

                The first one given by the code above

                nodeValue div nodeValue "Hello World!"

                var textNode = div.firstChild; / / or div..childnodes [0]Copy the code

                Once you have a reference to the text node, you can modify it as follows.

                div.firstChild.nodeValue = "Some other message";Copy the code

                If the text node currently exists in the document tree, the result of modifying the text node is immediately reflected. Also, when modifying the text node, note that the string is encoded in HTML (or XML, depending on the document type). In other words, less-than, greater-than, or quotes are escaped as in the following example.

                // The output is "Some"other message"
                div.firstChild.nodeValue = "Some other message";Copy the code

                Rather, this is an efficient way to htML-encode a DOM document before inserting text into it.

                In IE8, Firefox, Safari, Chrome, and Opera, Text type constructors and stereotypes can be accessed through scripts.

                Creating a text node

                You can create a new text node using document.createTextNode(), which takes one parameter — the text to be inserted into the node. As with setting the value of an existing text node, the text as a parameter is encoded in HTML or XML format.

                var textNode = document.createTextNode("Helloworld!" );Copy the code

                When a new text node is created, the ownerDocument property is also set for it. However, we will not see the new node in the browser window unless it is added to an existing node in the document tree. The following code creates one

                var element = document.createElement("div"); element.className = "message"; var textNode = document.createTextNode("Hello world!" ); element.appendChild(textNode); document.body.appendChild(element);Copy the code

                This example creates a new

                "message" class

                In general, each element has only one text child node. However, it is possible to have multiple text child nodes in some cases, as shown in the following example.

                var element = document.createElement("div"); element.className = "message"; var textNode = document.createTextNode("Hello world!" ); element.appendChild(textNode); var anotherTextNode = document.createTextNode("Yippee!" ); element.appendChild(anotherTextNode); document.body.appendChild(element);Copy the code

                If two text nodes are adjacent siblings, the text in the two nodes is displayed together without Spaces.

                Normalized text node

                The presence of adjacent sibling text nodes in a DOM document can easily lead to confusion because it is not clear which text node represents which string. In addition, adjacent text nodes are not uncommon in DOM documents, which leads to a method of merging adjacent text nodes. This method is defined by the Node type (and therefore exists in all Node types) and is called normalize(). If the normalize() method is called on a parent element containing two or more text nodes, it consolidates all text nodes into one node, resulting in nodeValue equal to the concatenated nodeValue of each text node before the merging. Let’s look at an example.

                var element = document.createElement("div"); element.className = "message"; var textNode = document.createTextNode("Hello world!" ); element.appendChild(textNode); var anotherTextNode = document.createTextNode("Yippee!" ); element.appendChild(anotherTextNode); document.body.appendChild(element); console.log(element.childNodes.length); // 2 element.normalize(); console.log(element.childNodes.length); // 1 console.log(element.firstChild.nodeValue); // "Hello world! Yippee!"Copy the code

                Browsers never create adjacent text nodes when parsing documents. This happens only as a result of DOM manipulation.

                Split text node

                The Text type provides a method called splitText() that does the opposite of normalize(). This method splits a text node into two text nodes, dividing the nodeValue by the specified location. The original text node will contain the content from the start to the specified location, and the new text node will contain the rest of the text. This method returns a new text node with the same parentNode as the original node.

                The Comment type

                Comments are represented in the DOM by the Comment type. The Comment node has the following characteristics:

                • nodeTypeIs 8;
                • nodeNameThe value of"#comment";
                • nodeValueThe value of is the content of the comment;
                • parentNodeMay beDocumentElement;
                • No child nodes are supported.

                The Comment type inherits from the same base class as the Text type, so it has all the string manipulation methods except splitText(). Like the Text type, the content of an annotation can also be retrieved via the nodeValue or data attribute.

                A comment node can be accessed through its parent, as shown in the following code.

                
                      
                Copy the code

                In this case, the comment node is

                var div = document.getElementById("myDiv");
                var comment = div.firstChild;
                console.log(comment.data);    // "A comment"Copy the code

                Alternatively, you can create a comment node using document.createcomment () and passing comment text to it, as shown in the following example.

                var comment = document.createComment("A comment ");Copy the code

                Obviously, annotation nodes are rarely created and accessed by developers, because annotation nodes have little impact on the algorithm. In addition, the browser does not recognize the comments that follow the tag. If you want to access comment nodes, make sure they are between and.

                Attr type

                The attributes of elements are represented in the DOM as Attr types. The constructors and stereotypes of the Attr type are accessible in all browsers, including IE8. Technically, attributes are nodes that exist in the attributes attribute of an element. The feature node has the following characteristics:

                • nodeTypeIs 11;
                • nodeNameIs the name of the feature;
                • nodeValueThe value of is the value of the property;
                • parentNodeThe value ofnull;
                • Child nodes are not supported in HTML.
                • In XML the neutron node can beTextorEntityReference.

                Although they are nodes, features are not considered part of the DOM document tree. The getAttribute(), setAttribute(), and remveAttribute() methods most commonly used by developers rarely refer directly to feature nodes.

                The Attr object has three attributes: name, value, and Specified. Where name is the property name (same as the value of nodeName), value is the property value (same as the value of nodeValue), and Specified is a Boolean value to distinguish whether the property is specified in the code or default.

                Use document.createAttribute() and pass in the name of the attribute to create a new attribute node. For example, to add the align feature to an element, use the following code:

                var attr = document.createAttribute("align");
                attr.value = "left";
                element.setAttributeNode(attr);
                console.log(element.attributes["align"].value);       // "left"
                console.log(element.getAttributeNode("align").value); // "left"
                console.log(element.getAttribute("align"));           // "left"Copy the code

                After you add a feature, you can access it in any of the following ways: the Attributes attribute, the getAttributeNode() method, and the getAttribute() method. Where attributes and getAttributeNode() both return the Attr node of the attribute, getAttribute() returns only the value of the attribute.

                DOM manipulation

                Most of the time, DOM manipulation is fairly concise, so it’s not a hassle to generate content in JavaScript that would normally be generated in HTML code. There are times, however, when manipulating the DOM is not as easy as it seems. Because browsers are riddled with hidden traps and incompatibilities, dealing with some parts of the DOM in JavaScript code is more complicated than others.

                Dynamic script

                use

                The code to create this DOM node looks like this:

                function loadScript(url){
                    var script = document.createElement("script");
                    script.type = "text/javascript";
                    script.src = url;
                    document.body.appendChild(script);
                }Copy the code

                Here is an example of calling this function:

                loadScript("client.js");Copy the code

                Another way to specify JavaScript code is inline, as shown in the following example:

                
                    function sayHi(){
                        alert("hi");
                    }
                Copy the code

                Logically, the DOM code for the following operation is valid:

                var script = document.createElement("script"); script.type = "text/javascript"; script.appendChild(document.createTextNode("function sayHi(){alert('hi'); } ")); document.body.appendChild(script);Copy the code

                This DOM code works fine in Firefox, Safari, Chrome, and Opera. But in IE, it causes an error. Var d = document.getelementById (“t”); document.writeln(d.firstChild.innerHTML); / /??? document.writeln(d.lastChild.innerHTML); / /???

                
                
                
                      
                aaa bbb ccc var d = document.getElementById("t"); document.writeln(d.childNodes[1].innerHTML); // ??? document.writeln(d.parentNode.getAttribute("name")); // ??? Copy the code
                
                
                
                      
                aaa bbb ccc var d = document.getElementById("t").childNodes[1]; document.writeln(d.nextSibling.innerHTML); // ??? document.writeln(d.previousSibling.innerHTML); // ??? Copy the code
                
                
                    
                      
                var t = document.getElementById("t"); console.log(t.class); // ??? console.log(t.getAttribute("class")); // ??? console.log(t.className); // ??? console.log(t.getAttribute("className")); // ??? console.log(t.style); // ??? console.log(t.getAttribute("style")); // ??? console.log(t.style.background); // ??? console.log(t.getAttribute("style.background")); // ??? console.log(t.wife); // ??? console.log(t.getAttribute("wife")); // ??? console.log(t.onclick); // ??? console.log(t.getAttribute("onclick")); // ??? Copy the code

                More and more

                Pay attention to wechat public number “Jie Ge she” reply to “answer”, get detailed explanation of the checkpoint. Focus on github.com/stone0090/j… To get the latest news.