jQuery参考实例 1.12 替换DOM元素
本文翻译自jQuery Cookbook (O’Reilly 2009) 1.12 Replacing DOM Elements
需求
替换DOM树中的节点
解决方案
可以用replaceWith()
方法来替换选中的DOM元素。在下面的代码中,所有class值为remove的<li>
元素都用replaceWith()
方法替换成新的DOM元素:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<ul>
<li class='remove'>name</li>
<li>name</li>
<li class='remove'>name</li>
<li class='remove'>name</li>
<li>name</li>
<li class='remove'>name</li>
<li>name</li>
<li class='remove'>name</li>
</ul>
<script type="text/JavaScript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
jQuery('li.remove').replaceWith('<li>removed</li>');
</script>
</body>
</html>
新的DOM元素由传入replaceWith()
方法的字符串参数决定。在上面的例子中,所有<li>
元素(连同其子元素)都被新的DOM元素<li>removed</li>
所替换。
讨论
jQuery还提供了一个操作上和replaceWith相反的方法:replaceAll()
。比如,上面的代码可以重写为:
jQuery('<li=>removed</li>').replaceAll('li.remove');
此处,jQuery函数接受的是一个HTML片段字符串。在根据该HTML片段字符串创建的DOM元素上调用replaceAll()
方法,可以替换replaceAll()
参数中选择的DOM节点。