jquery动态添加DOM节点

1、append()方法:向每个匹配的元素内部添加元素

    appendTo()方法:将所有匹配的元素追加的指定的元素中

<html>
<head>
     <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
     <title>jquery选择器</title>
</head>
<body>
    <ul>
        <li>苹果</li>
        <li>香蕉</li>
        <li>橘子</li>
        <li></li>
     </ul>
</body>
<script type="text/javascript">
    var $li1=$("<li>柚子</li>");
    $("ul").append($li1);
    var $li2=$("<li>哈密瓜</li>");
    $li2.appendTo("ul");
</script> </html>

2、prepend()方法:向所有匹配的元素前面添加新的元素

    prependTo()方法:将元素添加到指定元素的前面

<html>
<head>
     <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
     <title>jquery选择器</title>
</head>
<body>
    <ul>
        <li>苹果</li>
        <li>香蕉</li>
        <li>橘子</li>
        <li></li>
     </ul>
</body>
<script type="text/javascript">
    var $p=$("<p>请选择你喜欢的水果</p>");
    $("ul").prepend($p);

$p.prependTo("ul");
</script> </html>

3、after():在每个匹配的元素之后添加元素

    insertAfter():将元素插入到指定元素的后面

<html>
<head>
     <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
     <title>jquery选择器</title>
</head>
<body>
    <p>请选择你喜欢的水果</p>
    <ul>
        <li>苹果</li>
        <li>香蕉</li>
        <li>橘子</li>
        <li></li>
     </ul>
</body>
<script type="text/javascript">
    var $b=$("<b>您的选择是</b>");
    $("p").after($b);
   
    $b.insertAfter("p");
</script>
</html>

4、before() 在匹配的元素之前添加元素,效果同prepend()

    insertBefore() 将元素添加到指定元素之前,效果同prependTo()

原文地址:https://www.cnblogs.com/RANCY/p/4911768.html