Categories
Uncategorized

At the core of JS DOM manipulation

 

table of Contents:

1, the node type of Document Type

2, the Element type node type

3, the node type Text Type

4, integrated small sample – dynamically add external style file

5, find an element of extension methods

 

Continued articles, let’s look at three common node types.

Document Type

js indicates that the document by Document type.

In the browser, document object is an instance (inherited from Document type) of HTMLDocument, represents the entire HTML page.

Moreover, document object is a property of the window object, it can be accessed as a global object.

1, access to child nodes

There are two built-in shortcuts to access its child nodes, documentElement and childNodes

example:

<html>
<head>
    <title>Sample Pagetitle>
head>
<body>
    <p>Hello world!p>
body>
html>

 

This page through the browser parses that document contains only one child, ie element.

        //

Access to documents and the child node childNodes documentElement

var html = document.documentElement; //

Made a reference to the of

alert(html === document.childNodes[0]); // true alert(html === document.firstChild); // true

 

Further there is a body attribute directly to the element

        var body=document.body;

 

 

2, to access the document information

As an example of HTMLDocument, document objects there are no standard Document object attributes. These attributes provide some information on the web page document object performance: title, URL, domain, referrer

        //

Document information: title, URL, domain, referrer

var originalTitle = document.title; var url = document.URL; var domain = document.domain; var referrer = document.referrer;

 

3, find elements

Document type provides two methods for the getElementById () and the getElementByTagName ()

The elements made Id: getElementById (ID)

 

Suppose div fragment

Some text

 

This can be achieved following code element

var div = document.getElementById("myDiv"); //

Get references

element

 

note:

1, the above parameters must match exactly the case.

2, if the ID values ​​of the plurality of elements of the same page, the getElementById () returns only the first occurrence of the element in the document.

 

Made elements getElementsByTagName (tag name) under the label name

Return Value: 0 NodeList comprising a plurality of elements or, in an HTML document, this method returns a HTMLCollection object as a “dynamic” collection, which is very similar NodeList object.

Example: get the page all element

        //

Get the page all element

var images = document.getElementsByTagName("img"); alert(images.length); //

The number of images output

alert(images[0].src); //

src attribute of the first image output

alert(images.item(0).src); //

src attribute of the first image output

 

Element Type

This is the type most contact with us, HTML tags are all in the main structure of this type.

To access the element tag name, you can use the nodeName attribute, you can use tagName property; these two properties will return the same value. example:

    
Some text

 

So we can get this element and its label name like the following:

        alert(div.tagName); //"DIV"
        alert(div.tagName == div.nodeName); //true

 

div.tagName DIV output is not the div, in HTML, the tag name is always expressed in all caps.

 

1, HTML elements

HTMLElement All HTML element by type of representation, not directly through this type, also is represented by its subtype.

HTMLElement type directly inherited from the Element and added some properties.

Each HTML element there is the following standard features.

id, the unique identifier element in the document

title, additional descriptive information about the elements, generally displayed through the tooltip

lang, element content language code, rarely used

the dir, direction language is ltr or rtl (l: left, t: to, r: right), rarely used

className, the class corresponding to characteristics of the element, namely the elements specified class CSS

example:

<div id="myDiv" class="bd" title="Body text" lang="en" dir="ltr">Some textdiv>

 

Example: to obtain the standard characteristic values ​​js

        var div = document.getElementById("myDiv");
        alert(div.id);  //"myDiv"
        alert(div.className);  //"bd"

 

Other title, lang, dir made similar method

 

2, to obtain the characteristic values

Each element has one or more characteristics, the use of these features gives the corresponding additional information element or content.

DOM methods there are three main operating characteristics, namely getAttribute (), setAttribute () and removeAttribute ().

Then the above example, obtaining a characteristic value.

        alert(div.getAttribute("id")); //"myDiv"

        alert(div.getAttribute("class")); //"bd"

 

By getAttribute () method may obtain custom properties

    
Hello world!

 

Made a custom value:

    var geo = div.getAttribute("data-geo");

 

Native elements of the characteristic, can be accessed by the attribute of the DOM element itself, e.g. div.id,

Custom can only be accessed via the getAttribute ().

Attributes of these objects generally only made when a custom property only by getAttribute () method.

 

3, the characteristic value set

By setAttribute () method may operate either HTML attributes may also operate custom properties.

Attribute names set by this method will be unified to lower case.

If the attribute is not present creates the property and set the value.

        div.setAttribute("id", "someOtherId");
        div.setAttribute("class", "someOtherClass");
        div.setAttribute("data-date", "2019-9-1");

 

 

Native characteristics may be provided by the methods of attribute assignment.

        div.align = “left”;

 

Use removeAttribute () method to completely remove the element characteristics, such as

        div.removeAttribute(“class”);

 

Comprehensive Example: Creating elements

Use document.createElement () method to create new elements, example:

        //

1, create a

element

var div = document.createElement("div"); //

2, add features

div.id = "myNewDiv"; div.className = "box"; //

3, added to the document tree

document.body.appendChild(div);

 

 

Text Types

This type is relatively simple to introduce a method to create a text node, createTextNode (), 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);

 

DOM manipulation comprehensive example – add external style file

Style file as an example to introduce

   

Use js build this reference

        var link = document.createElement("link");
        link.rel = "stylesheet";
        link.type = "text/css";
        link.href = "style.css";
        var head = document.getElementsByTagName("head")[0];
        head.appendChild(link);

 

A function to encapsulate at

        function loadStyles(url) {
            var link = document.createElement("link");
            link.rel = "stylesheet";
            link.type = "text/css";
            link.href = url;
            var head = document.getElementsByTagName("head")[0];
            head.appendChild(link);
        }

 

Call the function:

loadStyles(“styles.css”);

 

Commonly used dynamic loading js files, may also have similar practices.

 

Find the extension element method

Selectors API

Document type we introduced by getElementById () and getElementsByTagName () to find the elements, but these two methods to query for some of the more personal a bit insufficient.

Selectors API allows the browser to support CSS native queries.

Can be selected via the DOM extension method to query the CSS breaks, the core of the two methods: querySelector () and querySelectorAll ()

querySelector () method takes a CSS selectors, returns the first element of the pattern matching, if not, return null

Example:

Gets the document first

element:

document.querySelector(“p”);

 

Gets the document class = “example” of the first element:

document.querySelector(“.example”);

 

Gets the document class = “example” of the first

element:

document.querySelector(“p.example”);

 

Obtaining documents have “target” attribute of the first elements:

document.querySelector(“a[target]”);

 

querySelectorAll () returns the instance of a NodeList.

As long passed querySelectorAll () method of CSS selectors effective, this method returns a NodeList object, regardless of how many elements match is found. If you do not find a matching element, NodeList is empty.

// get document all

elements

        var x = document.querySelectorAll(“p”);

// set the background color of a

element

        x[0].style.backgroundColor = “red”;

 

And inserting markers innerHTML outHTML

When obtain a modified html, direct labeling techniques using an insertion easier.

innerHTML and outHTML both DOM extension has been included in the HTML5 specification.

1, innerHTML property

   

       

            Hello world!

       

   

Corresponding to the above

element, its property returns the following string innerHTML

       

            Hello world!

       

2, outHTML property

   

       

            Hello world!

       

   

Corresponding to the above

element, its outerHTML property returns the same code as above, comprising a

itself.

The same value may be provided, such as

        var div = document.getElementById(“content”);

        div.outerHTML = ‘

remove div

‘;

 

to sum up

We introduced DOM1 level common operations, DOM1 main level is defined by the underlying structure of HTML and XML documents.

DOM2 and DOM3 level is introduced on the basis of this structure more interactive capabilities, also supports more advanced XML features, a common feature is used to set the style:

Any support style properties in JavaScript HTML element has a corresponding style property, we can use this property set the style, such as

        var div = document.getElementById(“content”);

        div.style.backgroundColor = “red”;

        div.style.border = “1px solid black”;

 

You can also use cssText, set multiple style properties are recommended.

div.style.cssText = “background-color:green; border:3px solid red;”;

The key to understanding the DOM, DOM is to understand the impact on performance.

Js DOM operations are often the largest part of the overhead should be minimized DOM operations.

(Reducing the number of operations by combining operation)

 

I wish Programming happy 🙂

 

Leave a Reply