1. Create nodes:
Nodes are the basis of the DOM structure. According to the DOM specification, nodes are a very broad concept, including elements, attributes, text, documents and comments. But in actual development, to dynamically create content, the main operating nodes include elements, attributes and text.
1. Requirements: Create an h1 tag and add it to the DOM node tree as a child node of the div element.
2. The basic idea is: first create an h1 element object and then add it to the document.
3. The following are two implementation methods:
// jQuery方式 var $h1 = $("<h1 title='创建节点' class='head'>jQuery与JavaScript创建节点比较</h1>"); $("div").append($h1);
//JavaScript方式 var div = document.getElementById("div1"); var h1 = document.createElement("h1");//创建h1对象 h1.setAttribute("title","创建节点");//为h1对象创建属性节点,并设置属性值 h1.setAttribute("class","head");//为h1对象成交价属性节点class,并设置属性值 var txt = document.createTextNode("jQuery与JavaScript创建节点比较"); h1.appendChild(txt);//将文本增加到元素节点中 div.appendChild(h1);//把创建的h1对象添加到div中
4. Comparison of the two methods:
1). Code input: jQuery creates element nodes with simple operation, only two lines of code. Can be implemented quickly. JavaScript implementation is cumbersome. Users need to create element nodes and text nodes separately, then add text nodes to element nodes step by step, and finally add them to the DOM structure tree.
2) Analysis from an execution perspective: In the Safari browser, the JavaScript implementation is more than 80 times faster than the jQuery implementation, and in the IE browser, which has the slowest execution speed, the difference between the two is more than 10 times