jQuery append()vs appendChild()

这是一些示例代码:

function addTextNode(){ var newtext = document.createTextNode(" Some text added dynamically. "); var para = document.getElementById("p1"); para.appendChild(newtext); $("#p1").append("HI"); } 
 

First line of paragraph.

append()appendChild()什么区别?
任何实时场景?

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

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

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

不再

now append是JavaScript中的一种方法

有关追加方法的MDN文档

引用MDN

ParentNode.append方法在ParentNode的最后一个子节点之后插入一组Node对象或DOMString对象。 DOMString对象作为等效的Text节点插入。

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

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

您可以传递多个参数。

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

append是一个jQuery方法,用于将一些内容或HTML附加到元素。

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

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

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

我知道这是一个陈旧且回答的问题,我不是在寻找选票,我只想添加一些额外的小东西,我认为这可能对新手有所帮助。

是的, appendChild是一个DOM方法, 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函数。

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

appendChild是一个纯javascript方法,其中append是一个jQuery方法。