• 技术文章 >web前端 >前端问答

    jquery怎么替换dom元素

    长期闲置长期闲置2022-06-17 19:41:16原创303

    方法: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 标签)。

    可能的值:

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

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

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

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

    输出结果:

    +5.gif

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

    以上就是jquery怎么替换dom元素的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:jquery
    上一篇:jquery怎样删除一个元素对象 下一篇:jquery获取input值有几种方式
    20期PHP线上班

    相关文章推荐

    • 【活动】充值PHP中文网VIP即送云服务器• jquery怎么移除一个元素• vue和jquery用什么语言• jquery怎么替换图片路径• jquery对象怎么转化为dom对象• jquery roundabout怎么用
    1/1

    PHP中文网