[JQuery]: CURD DOM operations of

//案例
<p title="location"> 你住在哪? </p>
<ul>
    <li title="温州">温州</li>
    <li title="杭州">杭州</li>
    <li title="广州">广州</li>
</ul>

First, access node

1, to obtain the contents of the text node

var $li = $("ul li:eq(1)"); //获取<ul>里的第二个li节点
var li_text = $li.text();   //获取其文本内容

2, node attributes Get

var $para = $("p");
var attr = $para.attr("title");//获取title属性值

Second, create a node

Create a node is not equivalent to adding a node, the node is not created in the document node tree.

1, create elements

var $li_0 = $("<li></li>");     //创建一个<li>元素,方式1
var $li_1 = $("<li/>");         //创建一个<li>元素,方式2

2. Create a text node

var $li_text = $("<li>苏州</li>");

3. Create an attribute node

var $li_attr = $("<li title='苏州'>苏州</li>");

Third, add nodes

Add twenty-two operations corresponding to:

  • append () and appendTo (): append new content within the element. (End internal)

  • prepend () and prependTo (): Front new content within the element. (The beginning of the internal)
  • after () and insertAfter (): insert new content after the element. (Two elements brotherhood)
  • before () and insertBefore (): insert new content before the element. (Two elements brotherhood)

$("ul").append($("<li> 新元素 </li>"));    //向ul内部追加新元素
$("<li> 新元素 </li>").appendTo($("ul"));  //效果相同

Add node operation, through the combination, it can be converted to the mobile node, as follows:

$("ul").append($("li:eq(1)"));//将第二个li移出,并添加到ul

Fourth, delete nodes

  • remove (): remove the node and all descendant nodes, delete nodes and returns a reference to possible secondary use.
var $ul = $("ul");
var $li = $("li:eq(1)").remove();   //将第二个li元素移除
$li.appendTo($ul);                  //将移除的li元素再次添加到ul中
  • empty (): remove all descendants of the node elements, but will retain the current properties of the object.

Fifth, the clone node

$("ul").clone(true).insertAfter($("ul"));//将ul列表复制一份添加到原表后面

clone method in the argument, the default is false, the new node after the copy does not have any behavior, if new elements of behavior can have an event, we need to set the parameter to true.

Sixth, the replacement node

$("p").replaceWith($("<strong>你住在哪?</strong>"));//用指定的DOM元素或HTML替换p元素
$("<strong>你住在哪?</strong>").replaceAll("p");    //与上相同

After the replacement, the event was originally bound elements will disappear, if necessary, again binding.

Seven parcels node

$("li").wrap("<strong></strong>");  //将li元素加粗

Guess you like

Origin www.cnblogs.com/summerday152/p/12401915.html