JQ DOM元素 创建 添加 删除

创建元素


// 创建元素节点
$('<p></p>'); // 创建属性节点
$('<p class="wow"></p>'); // 创建文本节点
$('hello world'); // 结合更实用
$('<p class="wow">hello world</p>');

添加元素

append() 在元素内部的结尾插入内容


$('p').append('<span>内部结尾</span>')

JQ DOM元素 创建 添加 删除

appendTo() 插入到所选元素内部的结尾

结果和 append() 一样 只是颠倒了位置


<p class="one">Always believe that good things are going to happen</p>
<p class="two">Always believe that good things are going to happen</p>
<p class="three">Always believe that good things are going to happen</p>
<span>new</span> <script>
$('span').appendTo('.two')
</script>

JQ DOM元素 创建 添加 删除

prepend() 在元素内部的开头插入内容


$('p').prepend('<span>内部开头</span>')

JQ DOM元素 创建 添加 删除

prependTo() 插入到所选元素内部的头部

结果和 prepend() 一样 只是颠倒了位置


<p class="one">Always believe that good things are going to happen</p>
<p class="two">Always believe that good things are going to happen</p>
<p class="three">Always believe that good things are going to happen</p>
<span>new</span> <script>
$('span').prependTo('.two')
</script>

JQ DOM元素 创建 添加 删除

### after() 在元素外部之后插入内容
```

$('p').after('<span>外部后面</span>')
![](https://images2018.cnblogs.com/blog/1321525/201809/1321525-20180907185454985-1055904183.png)
<br /> ### before() 在元素外部之前插入内容
$('p').before('<span>外部前面</span>')
![](https://images2018.cnblogs.com/blog/1321525/201809/1321525-20180907185623794-1105993898.png)

<br />

## 删除元素
### remove() 删除整个元素
<p>Always believe that good things are going to happen</p>
<span>Persist</span>
<p>Always believe that good things are going to happen</p>
<span class="txt">Persist</span> <script>
$('span').remove();
$('span').remove('.txt'); // 可筛选
</script>
![](https://images2018.cnblogs.com/blog/1321525/201809/1321525-20180908092327587-2000278392.png)

![](https://images2018.cnblogs.com/blog/1321525/201809/1321525-20180908092259179-1874399156.png)

<br />
### empty() 清空元素的所有子节点
<p>Always believe that good things are going to happen</p>
<span>Persist</span>
<p>Always believe that good things are going to happen</p>
<span class="txt"><a href="">Persist</a></span> <script>
$('span').empty();
</script>
![](https://images2018.cnblogs.com/blog/1321525/201809/1321525-20180908092541891-730462301.png)

<br />
上一篇:RPC框架实现


下一篇:vue基础篇---vue组件《2》