DOM [Introduction, DOM in HTML, DOM in XML]

What is DOM?

The DOM (Document Object Model) document object model is a language- and platform-neutral interface. .

Allows programs and scripts to dynamically access and update the content of documents .

Why use DOM?

Dom technology enables users to change pages dynamically, such as dynamically showing or hiding an element, changing their properties, adding an element, etc. Dom technology greatly enhances the interactivity of the page .

HTML DOM

HTML DOM is a memory object tree, only one copy is saved in the browser, and the content of HTML modified by HTML DOM will be directly reflected in the browser

 

write picture description here

 

API

NODE object API

In the eyes of the DOM, HTML is composed of different types of nodes, which all attribute NODE objects.

The NODE object has a nodeType property that can be used to determine the node type

 

write picture description here

 

There are connections between different types of HTML nodes:

  • A node above a node is the parent of that node
  • Nodes below a node are the children of that node
  • Nodes at the same level with the same parent are siblings
  • A node's next-level set of nodes is the node's descendants (descendants)
  • The parent, grandparent node and everything above the node are the ancestors of the node

Therefore, the NODE object also has attributes and methods for accessing nodes

Attributes:

 

write picture description here

 

 

write picture description here

 

In general, it is: get the information of the node (node ​​name, node value) and the brothers and fathers of the access node

method:

 

write picture description here

 

 

write picture description here

 

In general, it is: add, replace, delete child nodes, determine whether there are child nodes, clone child nodes

document

In the HTML DOM, we mentioned and used the document, a built-in object of Javascirpt a lot . Please note that this object can only represent the root node of HTML .

document properties:

  • documentElement [you can get <html>this node]

document method:

  • createElement() [create an element node]
  • createComment() [create comment]
  • createAttribute() [create attribute node]
  • createTextNode() [create text node]
  • getElementById() [get the element node by id]
  • getElementsByTagName() [Get an array of all tag names through tag names]

Element interface

Element represents the element node, which is an interface we often use!

Element property:

  • tagName [returns the capitalized name of the element tag ]

Element method:

  • getAttribute(String name) [get the value of the attribute]
  • setAttribute(String name,String value) [Set the name and value of the attribute, create it if it does not exist]
  • getElementsByTabName() [ returns an array of descendant nodes of this element node ]
  • removeAttribute() [remove attribute]

When we set properties, instead of calling methods to set them, we often do:


	var input = document.createElement("input");
	input.value = "aa";
	input.name = "bb";

DOM for XML

We may use XML files as client and server transport files. So we need to learn to manipulate XML documents through DOM in JavaScript code

The APIs of XML and HTML are very similar, so I won't go into details here.

load XML

If the client and server exchange data through XML files or XML strings. Then, we need to load the server's XML file or XML string into a DOM object in JavaScript.

The problem now is that IE and fireFox load XML differently . Therefore, we'd better encapsulate it into a method to load XML .

/**
 * @param flag true代表的是文件,false代表的是字符串
 * @param xmldoc 要封装成DOM对象的字符串或文件
 * @return 返回的是根节点的元素节点
 *	重点放在高版本上!!
 * */


function loadXML(flag, xmldoc) {

    //浏览器是低版本的IE
    var objXml;
    if (window.ActiveXObject) {

        //是IE的话,有两种方式来创建ActiveXObject对象
        var name = ["MSXML2.DOMDocument", "Miscrosoft.XmlDom"];
        for (var i = 0; i < name.length; i++) {
            objXml = new ActiveXObject(name);
            break;
        }

        //设置为同步【装载XML文件成DOM对象,我们都是同步操作】
        objXml.async = false;

        //如果是字符串
        if (flag == false) {
            objXml.loadXML(xmldoc);
        } else {
            //如果是文件
            objXml.load(xmldoc)
        }
        return objXml.documentElement;


        //浏览器是fireFox或者高版本的IE
    } else if (document.implementation.createDocument) {
        //字符串
        if (flag == false) {

            //创建对象,解析XML字符串
            objXml = new DOMParser();

            //解析到根节点
            var root = objXml.parseFromString(xmldoc, "text/xml");
            return  root.documentElement;


        } else {

            //由于安全问题,想要得到XML文件,需要通过XMLHttpRequest对象来获取
            objXml = new XMLHttpRequest();

            //同步
            objXml.open("GET", "1.xml", false);

            objXml.send(null);

            //返回XML数据
            return objXml.responseXML.documentElement;

        }
        //解析不了啦
    } else {
        alert("解析不了了");
    }

}

test

 

write picture description here

 

remove whitespace

Add this feature if needed!


function removeBlank(xml) {
    if (xml.childNodes.length > 1) {
        for (var loopIndex = 0; loopIndex < xml.childNodes.length; loopIndex++) {
            var currentNode = xml.childNodes[loopIndex];
            if (currentNode.nodeType == 1) {
                removeBlank(currentNode);
            }
            if (((/^\s+$/.test(currentNode.nodeValue))) && (currentNode.nodeType == 3)) {
                xml.removeChild(xml.childNodes[loopIndex--]);
            }
        }
    }
}



XPATH

In fact, we have already touched the XPATH technology. When explaining XML, we have already used the XPATH technology.

You can refer to my previous XML blog post: blog.csdn.net/hon_3y/arti…

XPATH can be divided into three types of searches in general:

  • Absolute path search (/root/child)
  • Relative path search (child node/child node) [The difference from absolute path search is whether there is a "/" at the beginning]
  • Full text search (//child nodes)

If we want to find attribute nodes, text nodes, and multi-condition nodes, we write XPATH like this

  • Attribute node: (first find the element node/@attribute name)
  • Text node: (find the element node/test() first)
  • Conditional query node: (find element node/[condition] first)
  • Multi-condition query node: (find the element node first/[condition][condition]) [two conditions match at the same time]
  • Multi-condition query node: (find element node/[condition] first | find element node/[condition] first) [or relationship]

When we used dom4j before, we called selectSingleNode() and selectNodes() methods to get nodes or multiple nodes of any depth

We want to use XPATH technology in JavaScript, then we also implement these two methods and call it!

selectSingleNode()

The selectSingleNode() method cannot be used under IE10 and IE11. Solution reference: wenda.so.com/q/145845351…

However, I did not solve the problem. . . . .

Below is the JavaScript code:


/**
 * 
 * @param xmldoc 代表的是XML的根节点
 * @param xpath 给出的XPATH表达式
 * @return 返回的是对应的节点或多个节点
 * 
 * 
 * 
 */
function selectSingleNode(xmldoc,xpath) {


    //如果是IE,IE10,IE11解决不了....会的人告诉我一声!!
    if(navigator.userAgent.indexOf(".NET")>0) {
        var value = xmldoc.selectNodes(xpath)
        return value;

    }else {

        //如果是fireFox
        var xpathObj = new XPathEvaluator();
        var value = xpathObj.evaluate(xpath, xmldoc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);

        return value.singleNodeValue;
    }

}
 


  • Test code:

    <script type="text/javascript" src="loadXML.js" ></script>
    <script type="text/javascript" src="xpath.js" ></script>

    <script type="text/javascript">

        function test() {

            var file = loadXML(true, "1.xml");

            var xpathValue = selectSingleNode(file, "//dd");
            var value = xpathValue;

            alert(value);

        }

    </script>
  • In fireFox, Chrome browser can get nodes normally

 

write picture description here

 

selectNodes()

Due to the above IE problem, I have not solved it yet, so I will test the FireFox browser directly .

When I review Jquery, I will fill in the hole here. . .

  • javascript code:
/**
 *
 * @param xmldoc 代表的是XML的根节点
 * @param xpath 给出的XPATH表达式
 * @return 返回的是节点数组
 */
function selectNodes(xmldoc,xpath) {

    var xpathObj = new XPathEvaluator();

    //如果是多节点,返回的是迭代器
    var iterator = xpathObj.evaluate(xpath, xmldoc, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);

    //把迭代器的数据写到数组中
    var arr = new Array();

    var node;
    while ((node=iterator.iterateNext())!=null) {
        arr.push(node);
    }

    return arr;

}
 
  • Test code:

        function test() {

            var file = loadXML(true, "1.xml");

            var xpathValue = selectNodes(file, "//aa");
            var value = xpathValue;

            alert(value);
        }

  • Effect:

 

write picture description here

 

If there are any mistakes in the article, please correct me, and we can communicate with each other. Students who are accustomed to reading technical articles on WeChat and want to get more Java resources can follow WeChat public account: Java3y

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325468054&siteId=291194637