天天看點

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");