Web front end lesson 29 – document node operation

Time:2021-10-10

1. Document node

The full name of DOM is   Document   Object   Model, namely document object model, is a set of rules for managing and controlling HTML documents, and document node is a concrete form of expression

If the whole HTML document is regarded as an object, the object is the document node, and the standard for how to operate and control the object is dom

DOM specifies that all elements in the HTML page are nodes, and all elements can be called through the document dot operator

The document node is also called document object. Every HTML document loaded into the browser will become a document object. Document is the root node of the HTML document

Therefore, in order to manipulate pages in scripts, document nodes and DOM rules are proposed

2. Document application exercise

Document scroll Title Exercise




    setInterval(function () {
        var tempTitle=document.title;
        var titleArr=tempTitle.split('');
        titleArr.push(titleArr.shift());
        var newTitle=titleArr.join('');
        document.title=newTitle;
    },600);

JavaScript timing events, two key methods:

Setinterval: executes the specified code continuously for the specified number of milliseconds

The clearinterval () method is used to stop the function code executed by the setinterval () method

SetTimeout to execute the specified code after delaying the specified number of milliseconds

The cleartimeout () method is used to stop the function code of the setTimeout () method

3. Document node properties

There are three types of attributes that are used more

①   doctype,documentElement,body,head,   Used to return a node inside the document

②   documentURI,URL,domain,lastModified,location,title,readyState,   Used to return the information specified in the document

③   anchors,forms,images,links,scripts,   Returns a collection of specific nodes within a document

4. Type I attribute

①   For HTML documents, document objects generally have two child nodes. The first child node is   DOCTYPE (the second is HTML)

The DOCTYPE node is an object that contains the type information of the current document. For HTML5 documents, the DOCTYPE node represents

Syntax: document. DOCTYPE;

②   The documentelement attribute represents the root node of the current document, usually the second child node of the document node, immediately following the document.doctype node

However, in general, other child nodes in the current page are accessed through the documentelement node

Syntax: document. Documentelement

③   The body property returns the body or frameset node of the current document. If there is no such node, it returns   null

Syntax: document. Body;

④   The head property returns the head node of the current document. If the current document has multiple heads, the first one is returned

Syntax: document. Head;

5. Type II attribute

①   The documenturi property returns the web address of the current document. All documents have this property

Syntax: document. Documenturi

②   The URL attribute returns the web address of the current document. The URL attribute is only available for HTML documents. This attribute is read-only and cannot be written

Syntax: document. URL

③   The domain property returns the domain name of the current document. If the domain name cannot be obtained, it returns   null

Syntax: document. Domain

④   The LastModified property returns the last modified timestamp of the current document (web page) in the format of string

Syntax: document. LastModified

Note that the return value of the LastModified property is a string, so it cannot be directly used for comparison. If you want to compare which time update of the two documents, you need to convert it to timestamp format

Syntax example: date. Parse (doc1. LastModified). The date. Parse method can convert a time format string into a timestamp format

⑤   The location property returns a read-only object that provides the URL information of the current document

Document.location.href, which returns the complete URL and can be written to (specify a new web address)

Document.location.protocol, which returns the current protocol

Document.location.host, return the domain name + port number of the current page

Document.location.hostname, return the domain name of the current page

Document.location.port, which returns the port number of the current page

Document.location.pathname, which returns the path of the current page in the server

Document.location.search, which returns the query string in the current page URL

Document. Location. Assign (‘Web address’), jump to another web address (similar to the first usage)

⑥   Location other content

The following methods have the same effect and can change the URL of the current page

Location. Assign (‘pass a URL ‘);

Window. Location = ‘pass a URL’;

Location. Href = ‘pass a URL’; (common method)

Reload (): reload the currently displayed page

location.reload(false):   // Reload from local cache first

location.reload(true):   // Reload from server first

Location object   The search property gets the string information of the page submission saved in the URL

⑦   The title property returns the title of the current document, which is writable

Syntax: document.title

When writing information: document. Title = ‘title written’;

⑧ The characterset property returns the character set that renders the current document, such as   UTF-8, iso-8859-1, etc

Syntax: document.characterset

⑨   The readyState property returns the status of the current document. There are three return values:

Loading indicates that the HTML code is loaded and the parsing has not been completed

Interactive, indicating the stage of loading external resources

Complete indicates that all loads are completed

console.log(document.readyState);
    var stateCheck=setInterval(function () {
        console.log(document.readyState);
        if (document.readyState=='complete'){
            clearInterval(stateCheck);
        }
    },500);

6. Category III attribute

These sets are dynamic, and any changes in the original node will be immediately reflected in the set

①   The anchors property returns all specified in the web page   Name attribute   A label element

②   The forms property returns all forms in the web page

③   The images property returns all the images in the web page

④   The links attribute returns all link elements (with href attribute) in the web page   A label)

⑤   The scripts property returns all scripts in the web page

Link first
    Link second
    Link third

    var coll=document.anchors;
    console.log(coll);  // Print all a tag elements with the name attribute defined, and the return value is combination
    console.log(typeof coll);  // The return value type is object
    console.log(coll[1]);  // Prints the specified a label element with the name attribute defined

  

 

7. Document select Page Elements

①   querySelector()   Method returns the element node that matches the specified CSS selector,

If multiple nodes meet the matching conditions, the first matching node is returned

If there is no node that meets the matching criteria, null is returned

Syntax: document. Queryselector (‘element selector)|   Class selector|   ID selector ‘);

②   querySelectorAll()   Method is used to filter page elements according to the specified selector

If multiple elements meet the matching criteria, the collection composed of these elements is returned

Syntax: document. Queryselectorall (‘selector name ‘);

The return value is a node list, not an array, but you can use the list like an array

If the search fails, it is not returned   Null, but returns an empty node list

③   Other common options

Getelementbyid(), return matching specified   Element node of ID attribute

Getelementbytagname(), returns all element nodes matching the specified tag

Getelementbyclassname(), returns all element nodes that match the specified class name

Getelementbyname(), returns all element nodes matching the specified name attribute

Note that the class name, ID name, etc. are directly used in the above method, not the selector name!!

8. Document create page elements and attributes

①   Createelement(), generate HTML element node

Syntax: VAR   Newelement = document. CreateElement (‘tag name ‘);   // The node name to be created needs quotation marks

Note that the page elements created by this method are not displayed directly in the page, but are stored in memory by default

② Appendchild(), which adds the created element to the specified parent element of the page

Syntax: parent element name. AppendChild (newelement);

③ Createtextnode(), which is used to add content to the new element. The parameter of the method is the text content node to be generated

Syntax: VAR elemtext = document. CreateTextNode (‘content of text node to be added ‘);

       newElem .appendChild(elemText);

In addition, you can also use   The innerHTML property sets or returns the HTML content between two tags

Syntax: element node (variable name). InnerHTML = ‘   text ‘;

④ The createattribute () method is used to create the attribute object node, and the return value is the attribute itself

Syntax: VAR   elemStyle=document.createAttribute(‘   Attribute name  ‘);

elemStyle .value=’color : red’;      // Assign a value to an attribute using. Value

⑤   The setattributenode () method is used to add an attribute node to an element, thereby realizing the attribute setting of the element

Syntax: newelem. Setattributenode (elemstyle);

var newElem=document.createElement('p');                        // Create < p > tag
    Var elemtext = document. CreateTextNode ('happy Valentine's day to single dogs in the world! ')// Create element content node
    newElem.appendChild(elemText);                          // Add content nodes to < p > tags
    var elemAttrStyle=document.createAttribute('style');           // Create style attribute
    // var elemAttrAlign=document.createAttribute('align');           // Create "align" attribute
    elemAttrStyle.value=('color:red;text-align:center;font-size:25px');     // Assign a value to the style attribute
    // elemAttrAlign.value=('center');               // Assign a value to the "align" attribute
    newElem.setAttributeNode(elemAttrStyle);                // Add the "style" attribute to the < p > tag
    // newElem.setAttributeNode(elemAttrAlign);                // Add the "align" attribute to the < p > tag
    var body=document.querySelector('body');                       // Select the < body > tab of the page
    body.appendChild(newElem);                              // Add the < p > tag to the page body

9. Methods of operating element attributes

One of the simplest ways to manipulate the CSS style of the element node is to use the following three methods of the node object to read, write, and delete the style attribute of the HTML element

① Getattribute(), get element attribute, syntax: element node. Getattribute (‘attribute name ‘);, The return value is the property value

② Setattribute(), set element attribute, syntax: element node. SetAttribute (‘attribute name ‘,’   Attribute value ‘);

③ Removeattribute(), delete element attribute, syntax: element node. Removeattribute (‘attribute name ‘);

10. Style attribute of element node

The element node itself also provides   The style attribute is used to manipulate CSS styles. The style attribute points to an object, which is used to read and write the inline CSS styles of page elements

var newElem=document.createElement('p');                        // Create < p > tag
    Var elemtext = document. CreateTextNode ('happy Valentine's day to single dogs in the world! ')// Create element content node
    newElem.appendChild(elemText);                          // Add content nodes to < p > tags
    newElem.style.textAlign='center';
    newElem.style.backgroundColor='hotpink';
    newElem.style.borderBottom='2px solid darkgreen';
    newElem.style.color='blue';
    newElem.style.fontSize='25px';
    newElem.style.cssFloat='none';                          // Float is a reserved word for JavaScript
    document.body.appendChild(newElem);                            // Add the < p > tag to the page body

Note: element   Style object corresponding element   Style attribute, style in style object and   The style names in the style attribute correspond to each other, but the writing rules are different

①   Remove the horizontal bar (-) from the CSS attribute hit, and then capitalize the first letter after the horizontal bar;

②   CSS attribute name is a reserved word of JavaScript, and “CSS” string prefix needs to be added before the attribute name;

③   The attribute values of the style object are strings, including units of measure

11. Csstext usage of style attribute

Style object   The csstext property can be used to directly read, write, and delete the entire style property

Syntax: element node. Style. Csstext = ‘style’;

var newElem=document.createElement('p');                        // Create < p > tag
    Var elemtext = document. CreateTextNode ('happy Valentine's day to single dogs in the world! ')// Create element content node
    newElem.appendChild(elemText);                          // Add content nodes to < p > tags
    newElem.style.cssText='text-align:center;color:blue;font-size:25px;border-bottom:2px solid darkgreen';
    document.body.appendChild(newElem);                              // Add the < p > tag to the page body

Delete entire   The style attribute can be used in this way

Csstext corresponds to the of HTML elements   Style attribute, so when writingYou do not need to overwrite the property name

12. Style attribute method

The style object provides three methods to read, write, and delete inline styles

① Setproperty(), set style, syntax: element node. Style. Setproperty() ‘   propertyName ‘ , ‘   value  ‘);

② Getpropertyvalue(), get style, syntax: element node. Style. Getpropertyvalue() ‘   propertyName ‘);

③ Removeproperty(), delete style, syntax: element node. Style. Removeproperty() ‘   propertyName ‘);

var newElem=document.createElement('p');                        // Create < p > tag
    Var elemtext = document. CreateTextNode ('happy Valentine's day to single dogs in the world! ')// Create element content node
    newElem.appendChild(elemText);                        // Add content nodes to < p > tags
    var elemStyle=newElem.style;
    elemStyle.setProperty('text-align','center');
    var queryRes=elemStyle.getPropertyValue('text-align');
    console.log(queryRes);
    elemStyle.removeProperty('text-align');
    document.body.appendChild(newElem);                            // Add the < p > tag to the page body

  

Recommended Today

Seven Python code review tools recommended

althoughPythonLanguage is one of the most flexible development languages at present, but developers often abuse its flexibility and even violate relevant standards. So PythoncodeThe following common quality problems often occur: Some unused modules have been imported Function is missing arguments in various calls The appropriate format indentation is missing Missing appropriate spaces before and after […]