天天看点

html如何添加或删除元素,添加、删除HTML元素

使用jQuery可以方便的添加新的HTML元素。

下面的方法用于添加HTML元素:

append() – 在指定的元素的尾部添加一个新内容。

prepend() -在指定的元素里前部添加新内容。

after() – 在指定元素前添加新内容

before() -在指定元素的后面添加新内容。

乍一看append,prepend 和after,before似乎功能一样,但append,prepend指在选中的元素本身(内部)的前面和后面,而after,before指在选择中的元素的前面和后面。

jQuery使用下面两个方法来删除或是清空某个HTML元素。

remove() – 删除指定的元素(包括其子元素)

empty() – 清空指定元素的子元素

例如:

JQuery Demo

$(document).ready(function () {

$("button").click(function () {

$("#div1").remove();

});

});

This is some text in the div.

This is a paragraph in the div.

This is another paragraph in the div.

Remove div element

JQuery Demo

$(document).ready(function () {

$("button").click(function () {

$("#div1").remove();

});

});

This is some text in the div.

This is a paragraph in the div.

This is another paragraph in the div.

Remove div element

html如何添加或删除元素,添加、删除HTML元素

empty() 示例:

[html]

JQuery Demo

$(document).ready(function () {

$("button").click(function () {

$("#div1").empty();

});

});

This is some text in the div.

This is a paragraph in the div.

This is another paragraph in the div.

Empty the div element

JQuery Demo

$(document).ready(function () {

$("button").click(function () {

$("#div1").empty();

});

});

This is some text in the div.

This is a paragraph in the div.

This is another paragraph in the div.

Empty the div element

html如何添加或删除元素,添加、删除HTML元素

jQuery的remove()方法也支持一个参数,可以用于过滤一些需要删除的HTML元素。这个参数可以为任何有效的jQuery selector.

比如下面代码只删除class=”italic”的

元素:

[javascript]

$("p").remove(".italic");

$("p").remove(".italic");