Search code examples
javascriptjquerydommove

Js - A more elegant / efficiant way of finding nth element in DOM than if-else


I need to move an element one level up in dom ...

So I made :

  jQuery(document).ready(function() {

  jQuery('.pricing-table .fancy-header').each(function() {
    jQuery(this).parent().before(this);
        })  

 });

and Also this is ok ..

var $node = jQUery('.pricing-table .fancy-header');
           jQuery($node).parent().before($node);
     })

And it works great ( http://jsfiddle.net/obmerk99/EdvTz/ ) , my problem is , that on some specific page loads, I might have 2 different .fancy-header elements and I need to move the first one UP and the second one DOWN ..

See Fiddle : http://jsfiddle.net/obmerk99/EdvTz/3/

Now , apart from some probable syntax mistake that makes it fail ( but that I can probably manage ) , my question is more about finding a more elegant and/or efficient way of doing so than a primitive if-else statement .

Is there such a way in jQuery ?


Solution

  • "Elegant" is subjective, but here's a short approach anyway.

    jQuery('.pricing-table .fancy-header').each(function (i) {
        jQuery(this).parent()[i ? "after" : "before"](this);
    });
    

    Since you'll only have one or two matches, we just use the counter to select either the "after" (if 1) or "before" (if 0) method.


    But for clarity, an if statement may be better. You can still use the i counter.

    jQuery('.pricing-table .fancy-header').each(function (i) {
        if (i)
            jQuery(this).parent().after(this);
        else
            jQuery(this).parent().before(this);
    });
    

    And here's efficient if that really matters (guessing not):

    jQuery('.pricing-table .fancy-header').each(function (i) {
        var par = this.parentNode;
        par.insertBefore(this, i ? par.nextSibling : par);
    });