移除元素
方法 | 说明 |
remove() | 从DOM中移除匹配的元素及其所有的后代和文本节点。 |
detach() | 从DOM中移除匹配的元素及其所有的后代和文本节点。还会在内存中保留副本。通常使用remove()方法。 |
empty() | 从DOM中移除匹配元素子节点及后代。 |
unwrap() | 移除匹配子节点及其后代。 |
<!DOCTYPE html>
<html> <head> <meta charset="UTF-8"> <title>remove</title> <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"> </script> </head> <body> <div> <ul id="ul"> <li>hgfd</li> <li>gffd</li> <li>hgfe</li> <li>hgef</li> </ul> </div> <button>移除元素</button> <script> $('button').on('click', function () { $('div').remove(); }); </script> </body></html>
<!DOCTYPE html>
<html> <head> <meta charset="UTF-8"> <title>remove</title> <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"> </script> </head> <body> <div> <ul id="ul"> <li>hgfd</li> <li>gffd</li> <li>hgfe</li> <li>hgef</li> </ul> </div> <button>删除元素</button> <script> $('button').on('click', function () { $('li').remove('#a'); }); </script> </body></html>
<!DOCTYPE html>
<html> <head> <meta charset="UTF-8"> <title>detach</title> <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"> </script> </head> <body> <div> <ul id="ul"> <li>hgfd</li> <li>gffd</li> <li>hgfe</li> <li>hgef</li> </ul> </div> <button>移除元素</button> <script> $('button').on('click', function () { $('div').detach(); }); </script> </body></html>
<!DOCTYPE html>
<html> <head> <meta charset="UTF-8"> <title>empty</title> <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"> </script> </head> <body> <div> <ul id="ul"> <li>hgfd</li> <li>gffd</li> <li>hgfe</li> <li>hgef</li> </ul> </div> <button>删除元素</button> <script> $('button').on('click', function () { $('li').empty(); }); </script> </body></html>
<!DOCTYPE html>
<html> <head> <meta charset="UTF-8"> <title>unwrap</title> <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"> </script> </head> <body> <div> <ul id="ul"> <li>hgfd</li> <li>gffd</li> <li>hgfe</li> <li>hgef</li> </ul> </div> <button>移除元素</button> <script> $('button').on('click', function () { $('ul').unwrap(); }); </script> </body></html>