Js instance
By zhangxinxu from www.zhangxinxu.com/wordpress/?… This article can be reprinted in full, but with the written permission of the original author, while retaining the original author and source, the abstract drainage is optional.
The DOM API is also being upgraded
Web front-end standards have been evolving for years, such as HTML5, CSS3, and the everyday ES6.
Then, there seems to be no then. In fact, in addition to HTML5/CSS3/ES6+, DOM standards are constantly being upgraded, and browsers are quietly following suit.
However, this kind of follow-up and support is very low-key and hidden; In addition, most of the discourse power of the industry is concentrated on JS engineers, and DOM this kind of thing is more “low-level” to support the scene, so all kinds of technical conference ah, sharing conference ah will never talk about this stuff.
So it’s easy to take his attention away, not realizing that the DOM manipulation part is actually pretty good now.
Before (),after(),prepend(),append(), etc
These new DOM API methods, which are relatively new, are designed to easily manipulate DOM elements using a very simple API like jQuery.
These apis include: before(), after(), replaceWith(), Append (), prepend().
1. DOM API之before()
Here before() is a ChildNode method, which is the node method. Node methods correspond to element methods. The difference is that nodes can be text nodes directly, or even comments, etc. However, elements must have HTML tags.
As a result, before() can be a DOM element, a DOM node, or even a character. Yes, it is very similar, and the semantics are the same, indicating that the current node is preceded by XXX.
The syntax is as follows:
Void childNode. before((node or string)... More nodes);Copy the code
You can see from the syntax that the before() method supports multiple arguments, and the arguments can be node objects or string objects.
As for the specific details, we can actually verify them through one example after another.
Let’s start with the simplest example, which is given the following HTML:
<img id="img" src="mm0.jpg">Copy the code
If we want to insert text before the image , we can do it:
Document.getelementbyid ('img'). Before (' beautiful: ');Copy the code
The effect would look like this:
What if we were to insert an HTML string? As follows:
Document.getelementbyid ('img'). Before ('<strong> beauty: </strong>');Copy the code
As a result, dangdang, THE HTML is escaped as safe plain text and displayed as follows:
You can see the difference between the native DOM’s before() API and jQuery’s before() API, where before() is treated as an HTML character, whereas before() is treated as a text character.
If we want to insert HTML content in front of the image, we can use the DOM node method, for example:
var eleTitle = document.createElement('h4'); Eletit. innerHTML = 'beauty: '; document.getElementById('img').before(eleTitle);Copy the code
It will behave as follows:
Some people may ask, what if I have to insert HTML character content in front of the image?
You can use the insertAdjacentHTML() DOM method, which is more compatible, as follows:
Document.getelementbyid ('img').insertadjacenthtml ('beforebegin', '<strong> Beauty: </strong>');Copy the code
The syntax is as follows:
element.insertAdjacentHTML(position, html);Copy the code
I won’t expand on it unless it is the focus of this article.
Another nice feature of the element DOM’s before() API is the ability to insert multiple node content at once, for example:
document.getElementById('img').before('1. Beauty ", ", "2. beauty");Copy the code
The effect is shown in the screenshot below:
All of the above before() effects can be felt here: DOM Before () node API method demo
Compatibility before() API Chrome54+, Firefox49+ only support, still relatively new, IE edge is not currently supported, see the following screenshot (real-time compatibility data) :
For some projects within the team or company, web pages such as management platforms or tools are safe to use apis like BEFORE (). What about user-oriented projects that require compatibility?
Simply add a polyfill JS code as follows (see MDN) :
/ / derived from https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/before ()/before (). The md (function (arr) { arr.forEach(function (item) { if (item.hasOwnProperty('before')) { return; } Object.defineProperty(item, 'before', { configurable: true, enumerable: true, writable: true, value: function before() { var argArr = Array.prototype.slice.call(arguments), docFrag = document.createDocumentFragment(); argArr.forEach(function (argItem) { var isNode = argItem instanceof Node; docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem))); }); this.parentNode.insertBefore(docFrag, this); }}); }); })([Element.prototype, CharacterData.prototype, DocumentType.prototype]);Copy the code
Note that Polyfill above does not support IE8 and below. The BEFORE () API can only be used in projects that are at least compatible with Internet Explorer 9.
Compared to insertBefore(), insertBefore() is an older and more traditional API that has the advantage of being compatible. The shortcoming is that its syntax is really strange. When A element is inserted in front of B element, the parent element parentNode. InsertBefore (newNode, referenceNode) is required. At least for so many years, I have not accurately remembered whether the parameter of insertBefore is the new node before or the node after the insertion.
The before() API, however, has a different syntax for inserting and relative nodes, which is easy to remember and error-prone, and has shorter API names.
2. DOM API之after()
The syntactic compatibility of after() and before() is one-to-one. The difference lies in semantics, where one is inserted before and the other after.
The syntax is similar, so you won’t have to go through each one. If you want to experience the after() feature, you can click here: DOM After () node API method demo
Then the following JS code polyfills the After () API, again, at least for IE9+ browsers.
/ / derived from https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/after ()/after (). The md (function (arr) { arr.forEach(function (item) { if (item.hasOwnProperty('after')) { return; } Object.defineProperty(item, 'after', { configurable: true, enumerable: true, writable: true, value: function after() { var argArr = Array.prototype.slice.call(arguments), docFrag = document.createDocumentFragment(); argArr.forEach(function (argItem) { var isNode = argItem instanceof Node; docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem))); }); this.parentNode.insertBefore(docFrag, this.nextSibling); }}); }); })([Element.prototype, CharacterData.prototype, DocumentType.prototype]);Copy the code
3. DOM API之replaceWith()
The syntax is as follows:
Childnode. replaceWith((node or string)... More nodes);Copy the code
Replace the current node with the content of another node.
For example, replace all HTML comments on a page with plain text nodes that can be displayed.
The following JS code:
var treeWalker = document.createTreeWalker(document.body, NodeFilter.SHOW_COMMENT); while (treeWalker.nextNode()) { var commentNode = treeWalker.currentNode; // replace the commentNode with the text node commentnode.replacewith (commentnode.data); }Copy the code
For example, a comment on the page reads:
Click a button to execute the JS code above, and the comment content is displayed as normal text on the page, as shown in the screenshot below:
Seeing is believing, you can click here: DOM replaceWith() node API method demo
Is there any enlightenment to our development? For example, page templates can be placed in comments…
Also, if compatibility is required, the following JS polyfill can be used (refer to MDN) :
function ReplaceWith(Ele) { var parent = this.parentNode, i = arguments.length, firstIsNode = +(parent && typeof Ele === 'object'); if (! parent) return; while (i-- > firstIsNode){ if (parent && typeof arguments[i] ! == 'object'){ arguments[i] = document.createTextNode(arguments[i]); } if (! parent && arguments[i].parentNode){ arguments[i].parentNode.removeChild(arguments[i]); continue; } parent.insertBefore(this.previousSibling, arguments[i]); } if (firstIsNode) parent.replaceChild(this, Ele); } if (! Element.prototype.replaceWith) { Element.prototype.replaceWith = ReplaceWith; } if (! CharacterData.prototype.replaceWith) { CharacterData.prototype.replaceWith = ReplaceWith; } if (! DocumentType.prototype.replaceWith) { CharacterData.prototype.replaceWith = ReplaceWith; }Copy the code
4. DOM API之prepend()
The syntax is as follows:
Parentnode.prepend ((node or string)... More nodes);Copy the code
Inserts the contents of other nodes (as children) in front of the current node. This means the same thing as the prepend() API in jQuery, and it won’t take anyone familiar with jQuery a minute to learn these apis.
Like before(), after(), etc., it doesn’t expand repeatedly.
If you are interested, you can click here: DOM Prepend () node API method demo
After a messy click on the demo button, you’ll see that all inserts are displayed first:
Previously, to insert content at the beginning of an element node, you had to either use insertBefore() to find firstChild, or use the insertAdjacentHTML() or insertAdjacentElement() methods, which were tedious.
The prepend() API is simpler and more straightforward.
The compatibility is exactly the same as before(). For IE9+ support projects, you can assist polyfill with the following:
/ / derived from: https://github.com/jserz/js_piece/blob/master/DOM/ParentNode/prepend()/prepend().md (function (arr) { arr.forEach(function (item) { if (item.hasOwnProperty('prepend')) { return; } Object.defineProperty(item, 'prepend', { configurable: true, enumerable: true, writable: true, value: function prepend() { var argArr = Array.prototype.slice.call(arguments), docFrag = document.createDocumentFragment(); argArr.forEach(function (argItem) { var isNode = argItem instanceof Node; docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem))); }); this.insertBefore(docFrag, this.firstChild); }}); }); })([Element.prototype, Document.prototype, DocumentFragment.prototype]);Copy the code
5. DOM API Append ()
The syntax is as follows:
Parentnode.append ((node or string)... More nodes);Copy the code
Insert the contents of other nodes (as children) at the end of the current node. This is the same as the append() API in jQuery, except that HTML strings are not displayed directly.
You can click here: DOM Append () node API method demo
All button insertions are displayed after the image, which is the last display inside the container:
Polyfill is as follows:
/ / derived from: https://github.com/jserz/js_piece/blob/master/DOM/ParentNode/append()/append().md (function (arr) { arr.forEach(function (item) { if (item.hasOwnProperty('append')) { return; } Object.defineProperty(item, 'append', { configurable: true, enumerable: true, writable: true, value: function append() { var argArr = Array.prototype.slice.call(arguments), docFrag = document.createDocumentFragment(); argArr.forEach(function (argItem) { var isNode = argItem instanceof Node; docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem))); }); this.appendChild(docFrag); }}); }); })([Element.prototype, Document.prototype, DocumentFragment.prototype]);Copy the code
Third, concluding remarks
The reason why we use jQuery is the convenience of the DOM API, the internal compatibility that helps us solve a lot of problems, and the friendly extension and plug-in mechanism.
Today, the native DOM API takes advantage of jQuery and has many simple traversal API methods. If we paste some more Polyfill JS to fix compatibility; With ES5 many data processing methods; DOM Leave 3 event processing, etc.
Basically, there is no need to use jQuery’s reason, saved resource loading, improve performance, the code also installed back to bi li bi.
So, basically, irreversibly, in the near future, within a few years, there will be a little fashion for native DOM apis, native JS front-end applications, and jQuery will be less and less mentioned, completing its historical mission and receiving a lifetime achievement award.
Well, that’s all for this article.
Thanks for reading and welcome to exchange!
This article is an original article, and it will often update knowledge points and correct some mistakes. Therefore, please keep the original source for reprinting to facilitate traceability, avoid the misleading of old wrong knowledge and have a better reading experience. This paper addresses: www.zhangxinxu.com/wordpress/?…
(The end of this article)