0

This is my first post on StackOverflow, so at beginning I'm sorry for my not full fluent English ;) But I try explain with what I have problem.

Here is live example

http://codepen.io/anon/pen/JKGbdE

class S {
        constructor(selectors) {
            let self = this;

            
            this.elements(selectors);
        }

        elements(selectors) {
            this.selectors = selectors;

              
            let result = document.querySelectorAll(this.selectors);

            if( result.length == 1 ) {
                result = result[0];

                this.element = result;
            } else {
                this.elements = [].slice.call(result);
            }

            this.nodes = result;

            return this.nodes;
        }

        parent() {
            let self = this;


            if( !!this.element ) {
                
                this.nodes =  this.element.parentNode;

            } else {

                this.elements.forEach = (item, key) => {
                    self.elements[key] = item.parentNode;
                };

                this.nodes =  this.elements;
            }

            return this.nodes;
        }


        result(a) {
            return this.nodes;
        }
    }

    window.$ = (selectors) => {
        let el = new S(selectors);


        return el;
    };
 

    console.log('first ex: ', $('#el') )
    console.log('second ex: ', $('#el').parent() )
<html>
  <body>
    <div id="el">test</div>
    
  </body>
</html>

If you open browser console you will see something like this:

[Log] first ex: –

S {selectors: "#el", element: <div id="el">, nodes: <div id="el">, …} 

[Log] second ex: –

<body>…</body>

The second example is OK. I just want to return a HTML node. In the first example it should return only <div id="el />.

Any suggestions?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Sabre
  • 46
  • 3

1 Answers1

0

In first ex: you are returning new S(...) and in second ex: - this.nodes (DOM objects).

Unless you extend JS DOM manipulation, you cannot expect getting DOMObject as response with all subfunctions working - jQuery also cannot give you this possibility.

Try console.log(jQuery('.anything')) - it also returns an object that has DOM object as item (with index 0 to be exact).

You should change your code so it will always return S object.

pzmarzly
  • 778
  • 15
  • 29
  • Thank you for your answer. I know what jQuery returns, but... if I change this scrap of code ` constructor(selectors) { let self = this; return this.elements(selectors); } ` than first example will work, but second don't. How change code to be more universal? – Sabre Jun 09 '16 at 16:47