jQuery的文档处理操作

文档处理常用的函数:

append, appendTo   向每个匹配的元素内部追加内容

prepend, prependTo   向每个匹配的元素内部前置内容。

before, after, insertBefore, insertAfter 在每个匹配的元素之后或者前面插入内容。

wrap, unwrap  把所有匹配的元素用其他元素的结构化标记包裹起来。unwrap 表示移除直接父级元素

replaceWith 将所有匹配的元素替换成指定的HTML或DOM元素。

empty, remove, clone  删除匹配的元素集合中所有的子节点。

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="jquery-1.11.1.min.js"></script>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<p>I would like to say: </p>
<div>this is div1</div>
<div>this is div2</div>
<p class="test_p">I would like to say: test_p</p>
<div id="foo">Hello foo after</div>
<div id="foo2">Hello foo before</div>
<div class="test_wrap" style="color: red">
    <p class="test_p2">I would like to say: test_p2</p>
</div>


<p class="test_empty">Hello,<span>Person</span> <a href="#">and person</a></p>
<p class="test_remove">Hello,</p> how are <p>you?</p>
<b class="test_clone">Hello,</b>
<p>how are you?</p>

<p class="test_replace">Hello</p>
<p class="test_replace">cruel</p>
<p class="test_replace">World</p>

</body>
</html>

<script>
    $(function () {

        //append
        //$("p").append("<b>Hello</b>");


        //appendTo 剪切操作
        // $("p").appendTo("div");

        //prepend 向每个匹配的元素内部前置内容
        //$("p").prepend("<b>Hello</b>");

        //after 在每个匹配的元素之后插入内容。
        //$("p").after("<b>Hello</b>");

        // before 在每个匹配的元素之前插入内容。
        // $("p").before("<b>Hello</b>");

        // 剪切操作
        //insertAfter 把所有匹配的元素插入到另一个、指定的元素元素集合的后面 和$("#foo").after("p")相同
        // $("p.test_p").insertAfter("#foo");
        //$("#foo").after($("p.test_p"));

        //insertBefore 把所有匹配的元素插入到另一个、指定的元素元素集合的前面。 和 与 $("#foo").before("p")相同。
        // $("p.test_p2").insertBefore("#foo2");
        // $("#foo2").before($("p.test_p2"));

        //wrap。把所有匹配的元素用其他元素的结构化标记包裹起来
        // $("p.test_p2").wrap("<div class='wrap' style='color: red;'></div>");

        //unwrap 取消包裹, 移除直接父级元素
        // $("p.test_p2").unwrap();

        //empty 删除匹配的元素集合中所有的子节点。
        // $("p.test_empty").empty();

        //remove 从DOM中删除所有匹配的元素。
        // $("p.test_remove").remove();

        //clone 克隆所有b元素(并选中这些克隆的副本),然后将它们前置到所有段落中。
        // $("b").clone().prependTo("p");

        //replaceWith 将所有匹配的元素替换成指定的HTML或DOM元素。
        //$("p.test_replace").replaceWith("<b>Paragraph. </b>");

    });
</script>

猜你喜欢

转载自blog.csdn.net/qq_15652607/article/details/82823510