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> |
有实时场景吗?
主要区别在于
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是JavaScript中的方法
有关添加方法的MDN文档
报价MDN
The
ParentNode.append method inserts a set of Node objects orDOMString objects after the last child of theParentNode .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 |
1 | $('#example').append('Some text or HTML'); |
1 | document.getElementById('example').appendChild(newElement); |
我知道这是一个古老且可以回答的问题,我不是在寻求选票,我只是想添加一点我认为可能会对新来者有所帮助的东西。
是的,
那么您可以将其添加到DOM中,而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> ") |