06 DOM操作之插入节点

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div class="box">

    </div>
    <script src="./jquery-3.5.1.js"></script>
    <script>

        $(function(){
            //1.后置追加每次加到后面
            //append() 向每个匹配的元素内部追加内容或者元素、字符串、jquery对象
            $('.box').append('<h2>hello</h2>')

            //appendTo() 将所有匹配的元素追加到指定元素中
            $('<h4>老村长</h4>').appendTo('.box').css('color','green').click(function(){
                console.log(this);//返回<h4>老村长</h4> js节点对象
                console.log($(this).text())//老村长
            });//返回的是h4jQuery对象

            //2.前置追加每次加到第一个元素
            //prepend
            $('.box').prepend('<a href="#">百度一下</a>')

            //prependTo
            $('<a href="#">百度一下2</a>').prependTo('.box')

            //after() 在每个匹配的元素之后插入内容
            $('.box').after('lizzy')
            $('h2').after('<h1>zuoluo</h1>')

            //inserAfter 把某个元素插入到匹配元素之后
            $('<h3>老男孩</h3>').insertAfter('h1')

        })


    </script>
</body>
</html>
posted @ 2020-12-24 15:40  *!Walter!*  阅读(54)  评论(0编辑  收藏  举报