The example in this article describes how JQuery creates DOM nodes. Share it with everyone for your reference. The specific analysis is as follows:
Use the JQuery selector to quickly and easily find a specific element node in the document, and then use the attr() method to obtain the values of various attributes of the element. But real DOM manipulation is not that simple. In DOM operations, it is often necessary to dynamically create HTML content to change the presentation of documents in the browser and achieve various human-computer interaction purposes.
HTML DOM structure is as follows:
<p class="nm_p" title="欢迎访问脚本之家" >欢迎访问脚本之家</p> <ul class="nm_ul"> <li title='PHP编程'>简单易懂的PHP编程</li> <li title='JavaScript编程'>简单易懂的JavaScript编程</li> <li title='JQuery编程'>简单易懂的JQuery编程</li> </ul>
Create element node
For example, you want to create two
1. Create two
The first step can be completed using jQuery’s factory function $(), in the following format:
$(html);
The$(html) method will create a DOM object based on the incoming HTML markup string, wrap the DOM object into a jQuery object and return it.
First create two
var $li_1 = $("<li></li>"); // 创建第一个<li>元素 var $li_2 = $("<li></li>"); // 创建第二个<li>元素
Then insert these two new elements into the document, you can use methods such as append() in jQuery. The JQuery code is as follows:
var $parent = $(".nm_ul"); // 获取<ul>节点。<li>的父节点 $parent.append($li_1); // 添加到<ul>节点中,使之能在网页中显示 $parent.append($li_2); // 可以采取链式写法:$parent.append($li_1).append($li_2);
New element nodes created dynamically will not be automatically added to the document, but will need to be inserted into the document using other methods. When creating individual elements, be careful about closing tags and using standard XHTML formatting. For example, to create a
element, you can use $("
") or $(""), but do not use $("") Or uppercase $("
").Create text node
Two
The JQuery code is as follows:
var $li_1 = $("
As shown in the above code, creating text nodes is to write the text content directly when creating element nodes, and then use append() and other methods to add them to the document.
No matter how complex the HTML code in $(html) is, it must be created in the same way. For example $("
Create attribute node
Creating attribute nodes is similar to creating text nodes, and is also created directly when creating element nodes. The JQuery code is as follows:
var $li_1 = $("<li title='新增节点:数据结构'>新增节点:数据结构</li>"); // 创建第一个<li>元素 var $li_2 = $("<li title='新增节点:设计模式'>新增节点:设计模式</li>"); // 创建第二个<li>元素 var $parent = $(".nm_ul"); // 获取<ul>节点。<li>的父节点 $parent.append($li_1); // 添加到<ul>节点中,使之能在网页中显示 $parent.append($li_2); // 可以采取链式写法:$parent.append($li_1).append($li_2);
View the code through the browser source code tool, and you can see that the last two
I hope this article will be helpful to everyone’s jQuery programming.