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()


38 comments:

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

    ReplyDelete
  2. Worked perfectly, thanks!

    ReplyDelete
  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. 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
  13. 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
  14. 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
  15. 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
  16. - 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
  17. Impresión online en gran formato, Imprenta digital online imprimimos roll ups, photocalls, vinilos, lonas. Envío gratis

    ReplyDelete
  18. 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
  19. 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
  20. 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
  21. 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
  22. 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
  23. 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
  24. 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
  25. 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


  26. Thanks for sharing, if you want more benefits then remain connect with us.

    Pitrinec Perfect Keyboard Pro Crack

    ReplyDelete
  27. 토토사이트 이용을 하다 보면 먹튀 피해에 대한 두려움이 갑자기 생기거나 두려움을 가지고 이용하는 경우가 대반사입니다. 토토마추자는 그러한 두려움을 없애드리기 위해 만들어진 먹튀검증커뮤니티 입니다. 다양한 검증 활동을 통하여 축적된 데이터로 방문해 주시는 모든 회원님들께 무료로 제공해드리고 있습니다. 토토사이트를 이용 하는 회원님들은 메이저사이트를 이용하고 싶은 마음이 크다는 걸 알 수 있습니다. 하지만 해당 토토사이트가 메이저인지 아닌지 확인할 방법은 민간인에게 어려움이 있다는 걸 알 수 있습니다. 이용전 꼭 토토마추자를 통하여 먹튀검증 서비스를 받아보시기 바랍니다안전놀이터.
    국내에 합법 토토사이트는 배트맨토토 에서 발매하는 정식서비스만 이용을 할 수 있으나 배팅금액 제한이 있기에 우후죽순 사설토토사이트가 생겨나고 있습니다. 대체적으로 이를 방지를 하려면 배트맨토토 자체에서 배팅금액 한도를 늘리는 수밖에 없다고 생각됩니다.

    ReplyDelete
  28. forum podting refers to generating quality incoming links by taking part in online discussion forums. It permits you to post new posts and reply to previous ones to drive traffic to your web site.

    ReplyDelete
  29. GTA Online: The ULTIMATE 바둑이사이트 바둑이게임 Guide (Odds, Probabilities, and Strategies)

    ReplyDelete
  30. 우리카지노는 대한민국의 바카라 업계를 장악하고 있는 카지노사이트 입니다. 우리카지노가 대한 민국에서 장악한 바카라 시장점유율이 50%가 넘고 10년 넘게 온라인 바카라 시장을 장악해왔기 때문에 대한민국에서는 우리카지노를 모르는 사람은 드뭅니다. 이런 바카라 업계의 독보적인 입지 때문에 늘 유명하거나 최고만을 찾는 사람들이 카지노사이트를 찾을때는 늘
    우리카지노를 찾습니다.바카라를 처음 시작하시는 초보자분들에게도 우리카지노에서 카지노사이트를 시작하시기 좋은 환경입니다. 우리카지노사이트에서는 신규가입시 3만쿠폰을 지급 해주기 때문입니다. 사람들이 늘 1등만을 찾는 이유는 분명 있습니다. 다른 카지노사이트와는 달리 우리카지노를 이용하실시 에이전트를 끼고 게임을 하신다면 본사 이외에 활동쿠폰 및 오링쿠폰을 별도로 제공해주고 있기 때문입니다. 이러한 이유들 때문에 카지노사이트 업계에서 바카라를 즐기신다면 다들 우리카지노를 선호 하십니다. 카지노사이트에서 바카라를 이기기 물론 어렵습니다. 하지만 우리카지노의 에이전트를 끼고 바카라를 즐기신다면 승산이 있다고 봅니다. 우리카지노 에이전트의 연락처는 홈페이지로 연락하시면 언제든지 부담없이 소통가능 합니다. 카지노사이트를 선정할때는 바카라를 다른곳보다 유리하게 즐길 수 있는 카지노를 선택해야한다고 생각합니다. 그것이 바로 우리카지노 입니다. 이상으로 우리카지노와
    바카라 카지노사이트 사이의 상관관계를 알아보았습니다바카라사이트.

    ReplyDelete
  31. Just 99 Web Design offers affordable web design packages for every business, from basic one-page websites to full eCommerce website design services. affordable web development

    ReplyDelete
  32. Ýnternet üzerinden gerçek bir casino hizmetine ulaþabilirsiniz. Gerçek casino salonlarýndan canlý casino hizmeti veren özel siteleri bulunmakta. Canlý casino siteleri gerçek casino salonlarýndan kullanýcýlarýna gerçek paralar üzerinden casino oyunlarý sunmakta canlı casino. Oyuncular internete baðlý olduklarý her yerden casino oyunlarý oynayabilmekte. Lakin bahsettiðimiz ve bahsedeceðimiz hizmetleri almak için doðru casino siteleri seçmeniz gerekmekte. Doðru siteleri yani güvenilir casino siteleri tercih ederek hem gerçek bir hizmet alýn hem de kazançlarýnýzý sorunsuz bir þekilde çekin.
    Sektörün en gözde casino þirketleri sayfamýzda paylaþýlmakta. Casino siteleri giriþ butonlarý üzerinden sitelere ulaþabilirsiniz. Sizlere sitelerin hizmetleri hakkýnda bilgiler vereceðiz. Sitelerin sunduklarý hizmetleri, bonuslarý ve finansal araçlarý hakkýnda bilgileri sizlere sunacaðýnýz. En iyi canlı casino sayfamýzdan ulaþabilirsiniz.
    Canlý casino
    Paylaþtýðýmýz siteler oyuncularýna gerçek casino salonlarýndan hizmet sunmakta. Oyuncular BlackJack, rulet, poker gibi casino masa oyunlarýný 4K görüntü kalitesi üzerinden gerçek casino salonlarýndan oynamakta. Ayrýca masa oyunlarý yanýnda özel oyunlarda bulunmakta. Canlý olarak sunulan oyunlar 4K görüntü kalitesi üzerinden oyunculara aktarýlmakta. Oyunlarýn sunumlarý canlý kurpiyerlerin sunumlarýyla yapýlmakta. Canlý casino oyunlarý kurpiyerlerin sunumlarýyla oynanmakta. Ayrýca masalarda bulunan herkes sizler gibi gerçek oyuncudur. Asla sitelerde bot hesaplarý bulunmaz. Herkes gerçek oyuncudur. Ayrýca odalarda sohbet bölümleri bulunmakta. Canlý casino
    oyunlarý oynanýrken ayný zamanda diðer oyuncular ile sohbet edebilirsiniz.
    Sitelerde poker, blackjack, rulet gibi onlarca farklý casino masa oyunlarý. Özel olarak hazýrlanan crayz time gibi canlý casino oyunlarý. Aviator, zeplin gibi popüler oyunlar ve binlerce farklý slot oyunlarý bulunmakta. Oyuncular istedikleri oyunlarý istedikleri bet üzerinden oynayabilmekte. Casino siteleri gerçek kumarhanelerdeki oyunlarý ve hatta daha fazlasýný kullanýcýlarýna sunmakta canlı casino.
    Lakin unutmayýn bahsettiðimiz hizmetleri en iyi casino siteleri için geçerli. Her canlý casino sitesi ayný hizmeti vermemekte. Bundan dolayý önünüze gelen her casino sitesi giriþ yapmayýn. Güvenilir casino siteleri giriþ yaparak gerçek bir hizmete ulaþýn.
    Oyuncular casino oyunlarýndan saðladýklarý kazançlarýný sorun yaþamadan çekebilmekte. Ayrýca istedikleri finansal yöntemi kullanarak seçebilmekte. Siteler oyuncular onlarca farklý finansal araç sunmakta. Kullanýcýlar istedikleri yöntemleri kullanarak para yatýrma ve çekme iþlemlerini kolay bir þekilde canlı casino yapabilmekte.
    Casino siteleri onlarca farklý bonus da vermekte. Yeni kayýt olan kullanýcýlar deneme bonusu ve free spin alarak bedava casino oyunlarý oynama fýrsatý yakalamakta. Ýlk yatýrýmlarýna özel casino hoþgeldin bonusu. Her yatýrýmlarýna özel casino yatýrým bonusu. Þansýz günlerinde ise casino kayýp bonusu alabilmekte. Ayrýca bahsettiðimiz bonuslar dýþýnda farklý casino bonuslarý da bulunmakta canlı casino.
    Deneme bonusu veren casino siteleri sayesinde kayýt olarak yatýrým yapamadan bedava casino oyunlarý oynayabilirsiniz. Siteler yeni üyelerine özel olarak bedava bonus vermekte.
    Bonusu alan kullanýcýlar bedava bir þekilde casino oyunlarý oynayarak ayrýca kazançlarýnýzý çekebilirsiniz.
    Güvenilir canlý casino siteleri sayesinde avantajlý bir hizmete ulaþýn.

    ReplyDelete