DOM替换replaceWith()和replaceAll()

本文介绍了jQuery中replaceWith()和replaceAll()方法的区别与应用实例,详细解释了如何使用这些方法来替换DOM元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

DOM替换replaceWith()和replaceAll()

.replaceWith( newContent ):用提供的内容替换集合中所有匹配的元素并且返回被删除元素的集合

简单来说:用$()选择节点A,调用replaceWith方法,传入一个新的内容B(HTML字符串,DOM元素,或者jQuery对象)用来替换选中的节点A

看个简单的例子:一段HTML代码

<div>
    <p>第一段</p>
    <p>第二段</p>
    <p>第三段</p>
</div>

替换第二段的节点与内容

$("p:eq(1)").replaceWith('<a style="color:red">替换第二段的内容</a>')

通过jQuery筛选出第二个p元素,调用replaceWith进行替换,结果如下

<div>
    <p>第一段</p>
    <a style="color:red">替换第二段的内容</a>'
    <p>第三段</p>
</div>

.replaceAll( target ) :用集合的匹配元素替换每个目标元素

.replaceAll()和.replaceWith()功能类似,但是目标和源相反,用上述的HTML结构,我们用replaceAll处理

$('<a style="color:red">替换第二段的内容</a>').replaceAll('p:eq(1)')

总结:

  • .replaceAll()和.replaceWith()功能类似,主要是目标和源的位置区别
  • .replaceWith()与.replaceAll() 方法会删除与节点相关联的所有数据和事件处理程序
  • .replaceWith()方法,和大部分其他jQuery方法一样,返回jQuery对象,所以可以和其他方法链接使用
  • .replaceWith()方法返回的jQuery对象引用的是替换前的节点,而不是通过replaceWith/replaceAll方法替换后的节点
  • <!DOCTYPE html>
    <html>
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <title></title>
        <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
        <style>
        .right div {
            background: yellow;
        }
        </style>
    </head>
    <body>
        <h2>replaceWith()和replaceAll()</h2>
        <div class="left">
            <button class="bt1">点击,通过replaceWith替换内容</button>
            <button class="bt2">点击,通过rreplaceAll替换内容</button>
        </div>
        <div class="right">
            <div>
                <p>第一段</p>
                <p>第二段</p>
                <p>第三段</p><p>第si段</p>
            </div>
            <div>
                <p>第四段</p>
                <p>第五段</p>
                <p>第六段</p>
            </div>
        </div>
        <script type="text/javascript">
        //只克隆节点
        //不克隆事件
        $(".bt1").on('click', function() {
            //找到内容为第二段的p元素
            //通过replaceWith删除并替换这个节点
            $(".right > div:first p:eq(1)").replaceWith('<a style="color:red">replaceWith替换第二段的内容</a>')
        })
        </script>
        <script type="text/javascript">
        //找到内容为第六段的p元素
        //通过replaceAll删除并替换这个节点
        $(".bt2").on('click', function() {
            $('<a style="color:red">replaceAll替换第六段的内容</a>').replaceAll('.right > div:last p:last');
        })
        </script>
    </body>
    </html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值