Introduction to new DOM methods such as before (), after (), prepend (), append ()

Source: Internet
Author: User
Tags hasownproperty

One, the DOM API is also constantly upgrading

Web front-end standards have been constantly upgraded, for example, for many years HTML5, CSS3, and every day to see ES6.

Then, there seems to be no then. In fact, in addition to the html5/css3/es6+, the DOM standards are constantly escalating, and browsers are quietly following up and supporting them.

However, this follow-up and support is very low-key and conceal, plus the industry's voice is mostly focused on the JS engineer, while the DOM this thing compared to the "low-level" can not afford the scene, so a variety of what technical conference ah, sharing the meeting AH absolutely will not talk about this thing.

So it was very easy to get his attention away, unaware that the DOM was working this piece, and now it's actually very powerful.

Second, before (), after (), prepend (), append () and other new Dom APIs

The next step is to introduce these new DOM API methods, all newer, designed to work with DOM elements in a very simple API, like jquery.

These APIs include:,,,, before() after() replaceWith() append() prepend() , well, an introduction below.

1. DOM API before ()

Here before() is a ChildNode method, that is, the node method. The node method corresponds to the element method. The difference is that nodes can be directly text nodes, even annotations, and so on. However, the element must have an HTML tag.

Therefore, before() the parameters can be either a DOM element or a DOM node, or even direct character content, gee, feel berthelot off the jquery before() API? Yes, it's really similar, and the semantics are the same, which means that the front of the current node is xxx.

The syntax is as follows:

void Childnode.before (node or string) ... other more nodes);

As you can see from the syntax, the Before () method supports multiple parameters, and the parameter can be either a node object or a String object.

As for the specifics, we can actually verify this by an example.

Let's look at one of the simplest examples, known as HTML:

If we want to insert the text in front of the picture, we can directly:

document.getElementById (' img '). Before (' Beauty: ');

The effect would be this:

What happens if we insert an HTML string? As follows:

document.getElementById (' img '). Before (' <strong> Belle:</strong> ');

As a result, when when, HTML was escaped into a secure plain text display, as follows:

You can see that the native Dom before() API and the API in jquery are before() still different, in jquery, before() the parameter values are treated as HTML characters, but this before() is handled as text characters.

If we want to insert HTML content in front of a picture, you can insert it using the DOM node, for example:

var eletitle = document.createelement (' h4 '); eletitle.innerhtml = ' beauty: ';d ocument.getelementbyid (' img '). Before ( Eletitle);

It will behave as follows:

Someone might be wondering, what if I have to insert HTML character content in front of the picture?

You can use a better-compatible insertAdjacentHTML() Dom method, using the following schematic:

document.getElementById (' img '). insertAdjacentHTML (' Beforebegin ', ' <strong> Belle:</strong> ');

The syntax is as follows:

element.insertadjacenthtml (position, HTML);

Not the focus of this article will not unfold.

The API for the element Dom before() also has a great feature of being able to insert multiple node content at the same time, for example:

document.getElementById (' img '). Before (' 1. Beauty ', ' ', ' 2. Beauty ');

The effect is as follows:

Demo Demos
All of the above before() effects can be ruthlessly clicked here: DOM before () Node API method Demo

Compatibility
before()API chrome54+,firefox49+ Support, is relatively new, IE Edge is not currently supported, see below (real-time compatible data):

For some projects within a team or company, a Web page such as a management platform or a tool, we can confidently use before() APIs such as those that are user-oriented for compatibility requirements.

Very simple, add a section of Polyfill JS code can be, as follows (refer to from MDN):

Originating from Https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/before ()/before (). 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]);

Note that the polyfill above does not support IE8 and the following browsers. before()that is, the API can only be used in projects that are at least compatible with IE9 browsers.

Comparison with InsertBefore ()
insertBefore()As an established traditional API, the advantage is good compatibility. Shortcomings, its syntax is really strange, a element inserted in front of the B element, the need for the parent element parentNode.insertBefore(newNode, referenceNode) , the Dadanaonao between the juniors involved in the father, obviously things will be troublesome. At least after all these years insertBefore the parameter is whether the new insertion node is inserted before or after the node, I did not accurately remember.

However, the API is different before() , the syntax only involves inserting nodes and relative nodes, very good remember, not error-prone, and the API name is shorter.

2. DOM API after ()

after()and before() the grammatical characteristics of compatibility are one by one corresponding, the difference lies in the semantics, one is inserted in front, one is inserted in the back.

Because the syntax is similar, therefore, does not have a signal, if you want to experience after() the characteristics of the performance, you can ruthlessly click here: DOM after () node API method Demo

Then the following JS code is polyfill to the after() API, as well, at least ie9+ browser.

Originating from Https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/after ()/after (). 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]);
3. DOM API ReplaceWith ()

Its syntax is as follows:

Childnode.replacewith (node or string) ... More nodes);

Represents the replacement of the current node with other node content.

For example, replace all HTML annotations on the page with a plain text node 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 comment node with the text node    commentnode.replacewith (Commentnode.data);}

For example, there is a comment on the page:

Click on a button to execute the above JS code, the result of this comment content becomes normal text display on the page, the effect is as follows:

Seeing is believing, you can click here: DOM replacewith () Node API method Demo

Are there any revelations about our development? For example, page templates can be placed in comments ...

Similarly, if you require compatibility, you can use the following JS Polyfill (refer to from 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.cr Eatetextnode (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;}
4. DOM API Prepend ()

Its syntax is as follows:

Parentnode.prepend (node or string) ... More nodes);

Represents the insertion of other node content (as a child node) at the front of the current node. Its meaning is the same as the API in jquery prepend() , and learning these APIs for people familiar with jquery is a matter of minutes.

Parameter value characteristics and before() so on, and after() so on, do not repeat the expansion.

If you are interested, you can click here: DOM prepend () Node API method Demo

After the button on the demo is a bit messy, you will find that all the insertions are displayed at the front:

In the past to want to insert the content at the top of the element node, either use insertBefore() firstChild the Find, or use insertAdjacentHTML() or insertAdjacentElement() method, are very verbose.

prepend () This API is simpler and more straightforward.

Compatibility and before() identical, for ie9+ support projects, you can assist the following polyfill:

Originating 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]);
5. DOM API Append ()

Its syntax is as follows:

Parentnode.append (node or string) ... More nodes);

Represents the insertion of other node content (as a child node) on the last side of the current node. The meaning is the same as the API in jquery, and the append() details are not supported by the difference in the direct display of HTML strings.

You can really click here: DOM append () Node API method Demo

All Click button Insert content is behind the picture, that is, the final display inside the container:

Polyfill as follows:

Originating 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]);
Iii. concluding remarks

Why we use jquery, one is the convenience of the DOM API, the other is the internal help us to solve a lot of compatibility issues, the third is the friendly extension and plug-in mechanism.

Today, the native DOM API draws on the advantages of jquery, but also a lot of simple traversal API methods, if we paste some polyfill js fix compatibility problem, and then ES5 a lot of data processing methods, DOM leave 3 event processing.

There's basically no reason to use jquery, which saves on resource loading, improves code performance, and also has a back-beep.

So, basically, already irreversible, in the near future, not a few years, the industry will rise up native Dom API, native JS development front-end application of the small fashion, jquery will be more and more not to be mentioned, complete its historical mission, in the future can receive a lifetime achievement award.

In addition, there is a class of jquery API This article does not introduce, for example Node.remove() , this API appears relatively early, and the previous introduction is not a wave out, so not put together to introduce.

Introduction to new DOM methods such as before (), after (), prepend (), append ()

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.