Home > Article > Web Front-end > Comparison summary of native JS and jQuery operating DOM
Some comparisons and summaries of native JS and jQuery operating DOM. This article summarizes a lot of comparisons. I believe it will be helpful to everyone’s study or work. Friends in need can refer to it. Let’s take a look together.
1. Create element nodes
1.1 Create element nodes with native JS
document.createElement("p");
1.2 jQuery creates element nodes
$('<p></p>');`
2. Create and add text nodes
2.1 Native JS Create text nodes
document.createTextNode("Text Content");
Usually creating text nodes is used in conjunction with creating element nodes, such as:
var textEl = document.createTextNode("Hello World."); var pEl = document.createElement("p"); pEl.appendChild(textEl);
2.2 jQuery creation and addition Text node:
var $p = $('<p>Hello World.</p>');
3. Copy node
3.1 Native JS copy node:
var newEl = pEl.cloneNode(true);
The difference between true and false:
3.2 jQuery copy node
$newEl = $('#pEl').clone(true);Note: To avoid duplicate IDs when cloning nodes
4. Insert node
4.1 Native JS adds a new child node to the end of the child node list
El.appendChild(newNode);Native JS inserts a new child node before the existing child node of the node:
El.insertBefore(newNode, targetNode);##4.2 In jQuery, there are many more ways to insert nodes than native JS
Add content at the end of the matching element's child node list
$('#El').append('<p>Hello World.</p>');
Add the matching element to the end of the target element's child node list
$('<p>Hello World.</p>').appendTo('#El');
Add content at the beginning of the matching element's child node list
$('#El').prepend('<p>Hello World.</p>');
Add the matching element to the beginning of the target element's child node list
$('<p>Hello World.</p>').prependTo('#El');
$('#El').before('<p>Hello World.</p>');
$('<p>Hello World.</p>').insertBefore('#El');
$('#El').after('<p>Hello World.</p>');
$('<p>Hello World.</p>').insertAfter('#El');
5. Delete the node
El.parentNode.removeChild(El);
$('#El').remove();
6. Replace node
El.repalceChild(newNode, oldNode);
Note: oldNode must be a real child node of parentEl
$('p').replaceWith('<p>Hello World.</p>');
7. Set properties/get properties
imgEl.setAttribute("title", "logo");
imgEl.getAttribute("title");
checkboxEl.checked = true;
checkboxEl.checked;
$("#logo").attr({"title": "logo"});
$("#logo").attr("title");
$("#checkbox").prop({"checked": true});
$("#checkbox").prop("checked");
Summary
The above is the entire content of this article. I hope the content of this article can bring some help to everyone's study or work. If you have any questions, you can leave a message to communicate.