关于javascript:jQuery append()vs appendChild()

jQuery append() vs appendChild()

这是一些示例代码:

1
2
3
4
5
6
function addTextNode(){
    var newtext = document.createTextNode(" Some text added dynamically.");
    var para = document.getElementById("p1");
    para.appendChild(newtext);
    $("#p1").append("HI");
}
1
2
    <p id="p1">First line of paragraph.<br />
</p>

append()appendChild()有什么区别?
有实时场景吗?


主要区别在于appendChild是DOM方法,而append是jQuery方法。您可以在jQuery源代码中看到的第二个使用第一个

1
2
3
4
5
6
7
append: function() {
    return this.domManip(arguments, true, function( elem ) {
        if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
            this.appendChild( elem );
        }
    });
},

如果在项目上使用jQuery库,则在向页面添加元素时始终使用append是安全的。


不再

现在append是JavaScript中的方法

有关添加方法的MDN文档

报价MDN

The ParentNode.append method inserts a set of Node objects or DOMString objects after the last child of the ParentNode. DOMString objects are inserted as equivalent Text nodes.

IE和Edge不支持此功能,但Chrome(54 +),Firefox(49+)和Opera(39+)支持。

JavaScript的追加类似于jQuery的追加。

您可以传递多个参数。

1
2
3
var elm = document.getElementById('div1');
elm.append(document.createElement('p'),document.createElement('span'),document.createElement('div'));
console.log(elm.innerHTML);
1
 


append是将某些内容或HTML附加到元素的jQuery方法。

1
$('#example').append('Some text or HTML');

appendChild是用于添加子元素的纯DOM方法。

1
document.getElementById('example').appendChild(newElement);

我知道这是一个古老且可以回答的问题,我不是在寻求选票,我只是想添加一点我认为可能会对新来者有所帮助的东西。

是的,appendChildDOM方法,append是JQuery方法,但实际上主要区别在于appendChild将节点作为参数,这意味着如果要向DOM添加空段,则需要首先创建该p元素

var p = document.createElement('p')

那么您可以将其添加到DOM中,而JQuery append会为您创建该节点并将其立即添加到DOM中,无论是文本元素还是html元素
或组合!

$('p').append(' I have been appended ');


appendChild是DOM vanilla-js函数。

append是jQuery函数。

他们每个人都有自己的怪癖。


JavaScript appendchild方法可用于将项目附加到另一个元素。 jQuery Append元素执行相同的工作,但肯定会减少行数:

Let us take an example to Append an item in a list:

a)使用JavaScript

1
2
3
4
5
6
7
8
var n= document.createElement("LI");                 // Create a
<li>
 node
var tn = document.createTextNode("JavaScript");      // Create a text node
n.appendChild(tn);                                   // Append the text to
<li>

document.getElementById("myList").appendChild(n);

b)使用jQuery

1
2
3
4
5
$("#myList").append("
<li>
jQuery
</li>
"
)

appendChild是纯JavaScript方法,其中append是jQuery方法。