PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

jquery怎么替换dom元素

WBOY
WBOY 原创
2022-06-13 17:35:02 1788浏览

方法:1、利用replacewith()方法,该方法用于集合中所有匹配的元素,语法为“元素对象.replacewith(content,function(index))”;2、利用replaceall()方法,该方法用于把被选元素替换为新的html元素,语法为“元素对象.replaceall(selector)”。

本教程操作环境:windows10系统、jquery3.6.0版本、Dell G3电脑。

jquery怎么替换dom元素

1、replaceWith() 方法

$(selector).replaceWith(content,function(index))

content 必需。规定要插入的内容(可包含 HTML 标签)。

可能的值:

  • HTML 元素

  • jQuery 对象

  • DOM 元素

function(index) 可选。规定返回替换内容的函数。

index - 返回集合中元素的 index 位置。

$(DOM).replaceWith(newContent) 用于替换集合中所有匹配的元素,并且返回被删除的元素集合:

<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="jquery.js"></script>
<script type="text/javascript">
$(&#39;document&#39;).ready(function (){
$(&#39;body>input&#39;).click(function (){
$(&#39;body>ul>li:gt(1)&#39;).replaceWith(&#39;<li>替换后的元素</li>&#39;)
})
})
</script>
</head>
<body>
<input type="button" value="替换">
<ul>
<li>第一个</li>
<li>第二个</li>
<li>第三个</li>
<li>第四个</li>
</ul>
</body>
</html>

输出结果:

+4.gif

2、replaceAll() 方法

$(newContent).replaceAll(DOM) 与 $(DOM).replaceWith(newContent) 方法功能一样,只不过是参数位置调换了一下(可以直接在后面赋予样式):

<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="jquery.js"></script>
<script type="text/javascript">
$(&#39;document&#39;).ready(function (){
$(&#39;body>input&#39;).click(function (){
$(&#39;<li>替换后的元素</li>&#39;).replaceAll(&#39;body>ul>li:gt(1)&#39;).css(&#39;color&#39;,&#39;orange&#39;);
})
})
</script>
</head>
<body>
<input type="button" value="替换">
<ul>
<li>第一个</li>
<li>第二个</li>
<li>第三个</li>
<li>第四个</li>
</ul>
</body>
</html>

输出结果:

+5.gif

视频教程推荐:jQuery视频教程

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。