Sunday, October 28, 2007

The missing JavaScript insertAfter() function

I really have no idea why the XML/HTML DOM lacks an insertAfter() function. It seems like a pretty common operation. Thankfully, the solution is simple. So, for those who are learning JavaScript and/or the DOM (and for those of us who are too lazy or tired to think), here's what we need to do, in effect:

function insertAfter(new_node, existing_node) {
  // if the existing node has a following sibling, insert the current
  // node before it. otherwise appending it to the parent node
  // will correctly place it just after the existing node.

  if (existing_node.nextSibling) {
    // there is a next sibling. insert before it using the mutual
    // parent's insertBefore() method.
    existing_node.parentNode.insertBefore(new_node, existing_node.nextSibling);
  } else {
    // there is no next sibling. append to the end of the parent's
    // node list.
    existing_node.parentNode.appendChild(new_node);
  }
} // insertAfter()


The function checks the existing node for a next sibling. If it has one, inserting after the current nodei is the same as inserting before the next.  If it doesn't have a next sibling, it assumes that the existing node is the last node under the parent. So, it may append the new node right under the parent.

Simple.

That should do it. Let me know if you have any problems with it.


ADDENDUM: As one commenter pointed out, insertBefore() should actually perform the correct appendChild() operation if existing_node.nextSibling is null. The function above makes this very explicit, which I tend to like. But, we can also simplify it, almost to the point of absurdity:

function insertAfter(new_node, existing_node) {
  existing_node.parentNode.insertBefore(new_node, existingNode.nextSibling || null);
} // insertAfter()


41 comments:

  1. Hi, your code has helped me. :) Many thanks, willowdan

    ReplyDelete
  2. Worked perfectly, thanks!

    ReplyDelete
    Replies
    1. HTML5 Training in Chennai HTML5 Training in Chennai JQuery Training in Chennai JQuery Training in Chennai JavaScript Training in Chennai JavaScript Training in Chennai Full Stack Developer Training in Chennai Full Stack Developer Training in Chennai


      AngularJS Training in Chennai AngularJS Training in Chennai Node.js Training in CHennai Angular 2 Training in Chennai Angular 2 Training in Chennai Node.js Training in CHennai Node.js Training in chennai MEAN Developer Training in Chennai

      Delete
  3. Excellent snippet. Thank you!

    ReplyDelete
  4. Thanks Jon - this is very helpful. I am not infatuated with you btw, but I like your sweet Javascript skillz.

    ReplyDelete
  5. Hi

    The test on existing_node.nextSibling is useless since insertBefore will have the right behaviour if existing_node.nextSibling is null (cf https://developer.mozilla.org/en/DOM/element.insertBefore).

    ReplyDelete
  6. You are correct, sir. I'm not entirely sure why I put an explicit test on nextSibling in this function at the time of this post.

    In any case, you can certainly omit the test on nextSibling unless you want some kind of special functionality in the case that the element is the last in the parent node.

    ReplyDelete
  7. Thanks! Very useful.

    ReplyDelete
  8. Hello everybody! can someone give me an exemple of use to this code, I'm trying it but it doesn't work, thanks

    ReplyDelete
  9. Thanks! Very useful.

    ReplyDelete
  10. Additionally, for certain elements you can pass in the value “-1″ before appending.
    For example:
    var row = table.insertRow(-1);
    for (var c= 0; c < 4; c++)
    {
    var cell = row.insertCell(-1);
    cell.appendChild(document.createTextNode(data[i++]));
    }

    ReplyDelete
  11. Very Elegant. Thanks.

    ReplyDelete
  12. This is my first visit to your blog, your post made productive reading, thank you. dot net training in chennai

    ReplyDelete
  13. Informative article, just what I was looking for.seo services chennai

    ReplyDelete
  14. Good post and I like it very much. By the way, anybody try this app development company for iOS and Android? I find it is so professional to help me boost app ranking and increase app downloads.

    ReplyDelete
  15. very nice blogs!!! i have to learning for lot of information for this sites...Sharing for wonderful information.Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.

    Web Designing Course Training in Chennai | Web Designing Course Training in annanagar | Web Designing Course Training in omr | Web Designing Course Training in porur | Web Designing Course Training in tambaram | Web Designing Course Training in velachery

    ReplyDelete
  16. Purchase EMAIL LEADS

    On the off chance that your organization is in the post for speculators or new business tries, business opportunity leads give you data of those needing to begin a business. They are an email away from being a purchaser or your business partner.Time is of the quintessence in each advertising methodology. purchase email lists Regular postal mail, for instance, takes an all-inclusive time from the mission time frame to usage. Not everything organizations can bear to invest such measure of energy to get advertising results. This might be one reason why email showcasing got famous. On account of modernization and high innovation, with your email contact show, you can reach and pass on your message to a huge number of individuals with only a couple clicks away.

    ReplyDelete
  17. Internet Download Manager 6.38 Build 10 IDM Crack Patch with Serial Crucial down load is a sort of shareware downloadmanager possessed by an American company called Tonec Inc.. IDM Patch Free Download captures any type of download in a extraordinary time limit and completes the download at a very brief time and at a faster speed as compared to any download manager right now. IDM company is based in nyc. This computer program is readily designed for Windows OS just for now.
    Presently IDM Serial Crucial Free has turned into a renowned application with over 20 million clients around the globe. Internet download manager Hack may take downloads from many browsers like Internet Explorer, Microsoft Edge, IDM Crack with Serial Key Google Chrome, Opera, Firefox for practically just about any kind of record of user's choice. It has gained control over down load; nevertheless, it shows its dialog box to an individual.

    ReplyDelete
  18. dubai internet directory has business listings, phone numbers, maps, email addresses and websites for local businesses in Dubai to help you get the job do.

    ReplyDelete
  19. Friendly Finance is South Africa's number 1 choice for finance - providing customers with all the information they need to make better financial decisions. We provide hundreds of comparisons of common consumer finance products, apply now such as personal loans, car loans, short-term loans and credit cards. Think of us as a helping hand in selecting consumer finance products.


    ReplyDelete
  20. Recently, the keto diet has become extremely popular for its health benefits such as weight loss and preventing disease. A custom Keto plan for life! Visit: keto diet macros

    ReplyDelete
  21. Health Experts have proven that regular exercise coupled with a good diet allow you to live longer and healthier. In this busy day and age, not everyone has the time to go to the gym - resulting to a lot of overweight people that desperately need to exercise. A healthy alternative is for you to Buy Home Gym Equipments that you can store in your own home or even at your office. Here are some tips when buying home gym equipment.

    First, know your fitness goals and keep these goals in mind when you are buying home gym equipment. One of the biggest mistakes that people make is buying the biggest or trendiest fitness machine simply because they like how it looks. More often than not, these end up gathering dust in your storage rooms or garage because you never end up using them. It is important to take note of what particular type of physical activity you want or enjoy doing before you buy your exercise machine. If you are looking to loose a few pounds and you enjoy walking or hiking, a treadmill is the best option for you. If you are looking to tone your lower body while burning calories a stationary bike is your obvious choice. Similarly, Special Equipments for Core Strength Exercises, Strength Training Weight Vests, Core Strength & Abdominal Trainers, Home Cardio Training, Strength Training Power Cages, Strength Training Racks & More.

    Second, set aside a budget before Buying Home Gym Equipments. Quality exercise machines do not come cheap. They are constantly exposed to wear and tear when they are used properly. So, pick machines that are built to last and have passed quality certifications to get the most out of your money. If you are operating on a tight budget, think about investing in several weights, We can Provide you High Quality Home Gym Equipments at Very Low Prices for your Complete Uses: Core Strength Exercises, Strength Training Weight Vests, Core Strength & Abdominal Trainers, Home Cardio Training, Strength Training Power Cages, Strength Training Racks & More.

    Its the Right Time to Buy Home Gym Equipments for you at Very Low Prices.

    ReplyDelete
  22. - Como organizar sua Semana com o Taskade - Segunda Feira, primeiro dia.
    - Como organizar sua semana com o Taskade - Terça - Vlog de Produtividade
    - Como organizar sua semana com o Taskade - Quarta
    - Como organizar sua semana com o Taskade - Quinta - Vlog Produtividade.
    Taskade - Sexta, Sábado e Domingo. Como foi e uma grande novidade

    ReplyDelete
  23. Impresión online en gran formato, Imprenta digital online imprimimos roll ups, photocalls, vinilos, lonas. Envío gratis

    ReplyDelete
  24. We are a clean skincare brand, 100% organic and made with what the earth has given us first. Our product formulations came from listening to our ingredients. From their benefits, scents and results, our products are truly science of the earth. https://www.fontshop.com/people/firstbase-skincare We wanted to step back from the long list of hard to pronounce scientific gibberish and provide ingredients relatable and understood. We are very proud to be one of the first few on the market to be ECO-Certified under the COSMOS standards, and for us we want to leave the earth better than we found it.

    ReplyDelete
  25. Are Anabolic Steroids and Body Building Supplements Safe to Use?


    Anabolic steroids and lifting weights supplements are a questionable way that numerous competitors and jocks to construct muscle. Frequently alluded to as these steroids, these enhancements are introduced in both regular and engineered structures. Heaps of the debate concerns the engineered structure because of the destructive results that weight lifters can experience the ill effects of. Characteristic anabolic enhancements will in general be less destructive whenever utilized with some restraint. In any case, Sp laboratories Anabolic steroids advance cell development and division, which is the regular standard behind weight training since it causes enormous muscles framed from more modest ones.

    Lifting weights Supplements have been demonized by a standing for an assortment of reasons. At the point when competitors and maltreatment of anabolic steroids muscle heads, they acquire an upper hand over their rivals. Thus, authorities in the game of cricket to weight training thought about anabolic steroids and enhancements contrary to the guidelines. This is apparent in the new outrages identified with baseball whizzes like Barry Bonds and Mark McGwire. During the 1980s, the World Wrestling Federation additionally experienced a major embarrassment that prompted the utilization of anabolic steroids and enhancements in the news. These and different outrages have added to the helpless standing of these questionable anabolic enhancements.

    Training on the impacts of anabolic steroids and enhancements is important to help direct individuals from them. Sadly, large numbers of the competitors in secondary school have gone to anabolic enhancements to help them acquire an upper hand against their rivals. With the constructive outcomes that are depicted by proficient competitors, more youthful clients are regularly unconscious of the ramifications as long as possible. Numerous anabolic steroids supplement clients experience the ill effects of hypertension, which can prompt a lot of genuine ramifications and can't be fixed on the body of the client.

    Despite the fact that steroids identical to a lot of debate, it isn't liberated from results positive. In the event that you need to assemble muscle quick, anabolic steroids and enhancements is one approach to do as such. They were additionally utilized in an assortment of clinical medicines until it was restricted in 1988. Pediatricians utilized anabolic to invigorate development in kids with hindered development chemical. Specialists likewise have utilized steroids to help malignancy and AIDS patients increment their hunger and fabricate bulk. Up to this point, specialists additionally used to prompt pubescence in young men. Presently, clinical medicines use testosterone for this reason and to assist competitors with recuperating wounds.

    Enhancements of manufactured steroids are dubious on the grounds that they give expanded strength and bulk, yet at extraordinary expense to the wellbeing of the client. The normal way, in any case, might be less hurtful. Regardless, even common anabolic maltreatment can be inconvenient to their wellbeing and bodies. By and large, can be the master or mentor to exhort you and assist you with finding the most valuable type of lifting weights material to assist you with accomplishing the best outcomes.

    ReplyDelete
  26. Buy Modafinil Online – Buying pills like Modafinil is not easy. Are you trying to purchase modafinil online? If your answer is Yes, then you are in the right place. In this buyer’s guide, we are going to cover everything you need to know about the most popular nootropic in the world.

    ReplyDelete
  27. Archie 420 Dispensary is a trusted Cannabis dispensary base in Los Angeles California USA. It is one of the top dispensary in this part of the country. White fire OG online for sales They do deliver Marijuana in the USA and to over 25 countries in the world. You can always visit their dispensary in Los Angeles using the address on their website. Place your order and get served by the best dispensary in the planet. Have fun.

    ReplyDelete
  28. Crystal online pharmacy is a trusted online drug store with a wide range of products to suit the needs of our clients. Buy research Chemicals online Crystal Pharmacy do strive to offer the best service and ship products world wide. All the products listed on our website are Ava in stock. Expect your order to be processed Immediately when you send us your request. We deal with varieties of drugs for our customers satisfaction. We cross barriers with our products and struggle hard to meet human satisfaction. When shopping with us, Be safe and secured and you will realize how swift we are with our services.

    ReplyDelete
  29. Why Your Online Business Needs A WordPress Website

    The WordPress site framework is currently the most generally utilized site building stage on the web, with more than 22% of all dynamic areas utilizing it. This site program has the usefulness to assist your online business with procuring income also giving as a total substance the board framework.

    There are in excess of 75 million WordPress sites on the web and it is supposedly utilized by numerous lofty associations. On the off chance that it is adequate for them, it will doubtlessly be sufficient for your online business.

    A Flexible Website Builder. wordpress pre built websites

    WordPress is an entirely adaptable program for an online business. You have the choice to post customary news things onto your site and make explicit item deals pages. You can decide to permit remarks on your pages which makes client created content as peruser's remarks. Updates can be planned for advance so that pages can go live at a pre-decided time and you can make certain pages private so just your clients with the particular URL can get to them.

    Creator Management.

    The program permits you to have numerous clients with various degrees of power. You can let others to make and add substance to your site without giving them full access rights to the whole site situation. You likewise can check and support any updates before they go live.

    WordPress Website Templates.

    At the point when a guest lands on your site, you just have seconds to dazzle them and convince them to remain. With the site layouts (called subjects) you can transfer an immense wide range of topics at the snap a catch. A few subjects are free and some have a little expense and there will be a topic that gives the look and highlights that you need for your online business. You can likewise effectively review and trade between subjects to see which one you like best.

    A WordPress Website Design To Suit You.

    The fundamental site download is a minimal programming system and you do have to add the additional items, or modules, to expand your site's abilities. Numerous modules are free and permit you to do various things including the formation of mailing records, contact structures, connect following, site design improvement frameworks, site investigation and the sky is the limit from there.

    Since there are so numerous WordPress sites on the web there are individuals everywhere on the world who create additional items, modules, topics for you to download to your site. What was once utilized for publishing content to a blog has now developed into an exceptionally incredible program to assist you with making a site that will attract the traffic and bring in cash for you.

    ReplyDelete
  30. Universal Gun sales is a trusted Firearm company base in Los Angeles California USA. It is one of the top Firearms Company in this part of the country. Buy CZ 75 P 01 Omega online They do offer the best firearms deal in the USA and to over 25 countries in the world. You can always visit their shop in Los Angeles using the address on their website. Place your order and get served by the best Firearm Company in the planet. Have fun.

    ReplyDelete
  31. If you're looking for free movies online feel free to visit the site. watch movie online You can watch unlimited movies and tv shows without any registration. Bazflix has thousands of movies and tv shows online.

    ReplyDelete
  32. Massage Mundaring is run by a talented female massage therapist and is based from her home studio in Mundaring. Trained in an introductory Traditional Thai Style Yoga massage course, in Northern Thailand mid 2015, Her eyes opened to the different cultural style of massage, which is offered fully clothed with pressing, here stretching, extending and rotating techniques focusing on meridian and acupressure points. Her chosen style of massage is Deep Tissue and Trigger Point which she believes to be powerful at unlocking and manipulating the muscle fibers, allowing new oxygen and blood to restore the tissue. Her technique is described by her clients as fluid, deep, rhythmic, releasing and restorative.

    ReplyDelete
  33. BCT Consulting is proud to announce a new location in century city California. For the past decade, we have been providing Web Design, managed IT support, and cyber security services to some of the biggest brands in Los Angeles.

    ReplyDelete