Several ways to add nodes in jQuery

Table of contents

1. append()

1. Basic use

2. Get a dom node and add it to the specified element, which is equivalent to cutting the element, and then add it as the last child element in the specified element

Two, prepend ()

3. before()

Four, after ()

5. appendTo()


1. append()

1. Basic use

  • Append the element to the parent element and be the last one
// 1、创建一个li标签
var li = $('<li>我是郑建</li>')
// 2、添加到ul中的元素后面
$('ul').append(li)

2. Get a dom node and add it to the specified element, which is equivalent to cutting the element, and then add it as the last child element in the specified element

// 1、获取一个li节点
var li = $('li')
// 2、把这个li标签剪切复制到ul中作为最后一个子元素
$('ul').append(li)

Two, prepend ()

The usage is the same as append()

3. before()

  • Element B.before(A), is to insert element A before element B and add it as a sibling element
var div1 = $('<div>我是新建的div</div>')
$('#div2').before(div1)

Four, after ()

  • Element A.before(B), is to insert element B behind element A and add it as a sibling element
var div1 = $('<div>我是新建的div</div>')
$('#div2').after(div1)

5. appendTo()

  • Syntax: child element.appendTo(parent element) ;//Add the child element as the last child element of the parent element
var li = $('<li>我是郑建</li>')
li.appendTo($('ul'))

Guess you like

Origin blog.csdn.net/qq_52421092/article/details/131252698
Recommended