0

I am creating my own library in JavaScript. I already made some basic functions like .css(), .text(), and etc. It works for me but when I add the two methods in one element it only apply the first method and ignoring the second one.

For example:

__('p').text('Hello World').css({'color':'red'});

Only the hello world will take effects, not the .css().
Here's my code:

function __(selector) {
    var _kean = {};

    _kean.selector = selector;

    if (typeof selector == 'object' || typeof selector == 'undefined') {
        _kean.element = [_kean.selector];
    } else if (typeof selector == 'string') {
        _kean.element = document.querySelectorAll(_kean.selector);
    } else if (selector instanceof HTMLElement) {
        _kean.element = [selector];
    } else {
        _kean.element = document.querySelectorAll(_kean.selector);
    }

    _kean.text = function(elems) {
        return [].slice.call(_kean.element).map(function(el, i) {
            if(!elems) return el.textContent;
                      return el.textContent = elems;
        });
        return _kean;
    }

    _kean.css = function(propval) {
        _kean.element.forEach(function(elements) {
            Object.assign(elements.style, propval);
        });
         return _kean;
    }

 return _kean;
}
Trish Siquian
  • 495
  • 3
  • 11
  • 22
  • *"and ignoring the second one*" - If you check the browser's console I think you'll find that it isn't "ignoring" so much as "crashing". Anyway, it doesn't make sense to chain anything *after* your `.text()` function, because the text function shown returns an array of text.. – nnnnnn Dec 12 '16 at 04:03
  • Not working sir – Trish Siquian Dec 12 '16 at 04:09
  • `return _kean;` should do it. Read the linked duplicate question, and perhaps some of the other questions linked to that question. – nnnnnn Dec 12 '16 at 04:09
  • Hey, I remember that code! Well, you need to think through what each function needs to return. When chaining, you’d need to return the object that has all the functions you’re going to call in the chain. That’d be `_kean`. It’s probably necessary to assign some results as properties to that object, instead of returning them, because those results (e.g. arrays) don’t have the functions you want to chain. – Sebastian Simon Dec 12 '16 at 04:10
  • Still not working sir :( – Trish Siquian Dec 12 '16 at 04:11
  • ** Thanks sir ! it works now for me, I just removed the `return` before the `[].slice` and I added `return _kean` each of the function!** – Trish Siquian Dec 12 '16 at 04:39

1 Answers1

0

The reason most APIs in JQuery are methods is so they can return the original object for you to chain another method to. To enable this functionality yourself, you need your methods to return the JQuery wrapped set that they were working with. That returned object will then support another method being called on it.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71