2

If I set a function under an object i can use it once only like

function handle(selector)
{
    return{
        elem:selector,
        next:function(){
            return (this.nextSibling.nodeType==1) ? this.nextSibling : this.nextSibling.nextSibling;
        }
    }
} 

here i can say handle.next() this will work but if I want to say handle.next().next().next() my question is how I can use in this way as jquery does?

Barmar
  • 741,623
  • 53
  • 500
  • 612
nikoss
  • 3,254
  • 2
  • 26
  • 40

1 Answers1

1

Speaking about your function you can modify it like this to make it work:

function handle(selector)
{
    if (typeof selector === 'string') {
        selector = document.querySelector(selector);
    }
    return{
        elem:selector,
        next:function(){
            return handle(selector.nextElementSibling);
        }
    }
} 

See jsfiddle.

UPD: Modified the code to support both elements and string selectors as a parameter.

UPD 2: Came out with an alternative variant. In this case we extend the native html element object and add new next method:

function handle(selector)
{
    if (typeof selector === 'string') {
        selector = document.querySelector(selector);
    }
    selector.next = function() {
        return handle(selector.nextElementSibling);
    };
    return selector;
}

Fiddle is here.

Yauheni Leichanok
  • 1,759
  • 1
  • 21
  • 30